{"text": "#include \"triangle_area_normal.h\"\n#include \n\nEigen::RowVector3d triangle_area_normal(\n const Eigen::RowVector3d & a,\n const Eigen::RowVector3d & b,\n const Eigen::RowVector3d & c)\n{\n ////////////////////////////////////////////////////////////////////////////\n Eigen::RowVector3d ab = b - a;\n Eigen::RowVector3d ac = c - a;\n\n // Compute the normal of the triangle\n Eigen::RowVector3d n = ab.cross(ac);\n\n // Compute the area of the triangle\n double area = (1.0 / 2.0) * n.norm();\n\n\n return area * n.normalized();\n ////////////////////////////////////////////////////////////////////////////\n}\n", "meta": {"hexsha": "4ad4a4d6d9b789f934d19019dcf24a1f15347079", "size": 619, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/triangle_area_normal.cpp", "max_stars_repo_name": "ericpko/computer-graphics-meshes", "max_stars_repo_head_hexsha": "ce4864fc671a4fad76299fa282e5e2ce681eba4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/triangle_area_normal.cpp", "max_issues_repo_name": "ericpko/computer-graphics-meshes", "max_issues_repo_head_hexsha": "ce4864fc671a4fad76299fa282e5e2ce681eba4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/triangle_area_normal.cpp", "max_forks_repo_name": "ericpko/computer-graphics-meshes", "max_forks_repo_head_hexsha": "ce4864fc671a4fad76299fa282e5e2ce681eba4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9130434783, "max_line_length": 78, "alphanum_fraction": 0.5040387722, "num_tokens": 146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947101574299, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7994111338597016}} {"text": "//\n// main.cpp\n// Forward Kinematics\n//\n// Created by Aziel Hutajulu on 01/03/22.\n//\n\n#include \n#include \n#include \n\nusing namespace std;\nusing namespace Eigen;\n\nint main() {\n //class for coordinate frame from 1 to i, coordinate frame 0 known as base coordinate\n class CoordFrame {\n public:\n //declaration of DH Convention\n double theta; //align x(i-1) with x(i), in degree\n double d; //align z(i-1) with z(i), in inch\n double a; //align O(i-1) with O(i), in inch\n double alpha; //rotation on x-axis to make z(i) paralel with z(i-1), in degree\n Matrix4d Ttheta, Td, Ta, Talpha, TM; // TM for Transformation Matrix\n \n //input for each coordinate frame\n CoordFrame (double x, double y, double z, double v){\n theta = x;\n d = y;\n a = z;\n alpha = v;\n }\n \n //function below to get transformation matriks for CF(i-1) to CF(i)\n Matrix4d getTransMatrix(){\n Ttheta << cos(theta), -sin(theta), 0, 0,\n sin(theta), cos(theta), 0, 0,\n 0, 0, 1, 0,\n 0, 0, 0, 1;\n Td << 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, d,\n 0, 0, 0, 1;\n Ta << 1, 0, 0, a,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n 0, 0, 0, 1;\n Talpha << 1, 0, 0, 0,\n 0, cos(alpha), -sin(alpha), 0,\n 0, sin(alpha), cos(alpha), 0,\n 0, 0, 0, 1;\n TM = Ttheta * Td * Ta * Talpha;\n return TM;\n }\n };\n \n //example declaratino of coordinate frame from Puma 260 Arm\n CoordFrame\n CF1(0, 13, 0, -90),\n CF2(0, -3, 8, 0),\n CF3(90, 0, 0, 90),\n CF4(0, 8, 0, -90),\n CF5(-90, 0, 0, 90),\n CF6(0, 5, 0, 0); //End Effector\n \n //example declaration for P0\n //P6 is the end effector\n Vector4d P0, P6;\n P0 << 1, 1, 1, 1;\n Matrix4d T06; //P0 = T06 * P6\n \n double Theta1, Theta2, Theta3, Theta4, Theta5, Theta6; // declaration for input theta\n \n cout << \"Angle of Rotation (degree) on:\" << endl << \"Joint 1 = \";\n cin >> Theta1;\n CF1.theta += Theta1;\n \n cout << \"Joint 2 = \";\n cin >> Theta2;\n CF2.theta += Theta2;\n \n cout << \"Joint 3 = \";\n cin >> Theta3;\n CF3.theta += Theta3;\n \n cout << \"Joint 4 = \";\n cin >> Theta4;\n CF4.theta += Theta4;\n \n cout << \"Joint 5 = \";\n cin >> Theta5;\n CF5.theta += Theta5;\n \n cout << \"Joint 6 = \";\n cin >> Theta6;\n CF6.theta += Theta6;\n cout << endl;\n \n //count the transformation matrix of CF(i-1) to CF(i)\n CF1.getTransMatrix();\n CF2.getTransMatrix();\n CF3.getTransMatrix();\n CF4.getTransMatrix();\n CF5.getTransMatrix();\n CF6.getTransMatrix();\n T06 = ((((CF1.TM * CF2.TM) * CF3.TM) * CF4.TM) * CF5.TM) * CF6.TM;\n \n //print the transformation matrix from base origin to end effector\n cout << \"Transformation Matrix from Base to End Effector:\" << endl << T06 << endl;\n \n //print end effector frame rotation matrix w.r.t. Base origin\n Matrix3d RotationMatrix;\n RotationMatrix << T06(0,0), T06(0,1), T06(0,2),\n T06(1,0), T06(1,1), T06(1,2),\n T06(2,0), T06(2,1), T06(2,2);\n cout << endl << \"End Effector frame Rotation Matrix w.r.t Base frame:\" << endl << RotationMatrix << endl;\n \n //print the position of end effector\n P6 = T06 * P0;\n cout << endl << \"Position of End Effector from Base Origin in inches:\" << endl << P6 << endl;\n}\n", "meta": {"hexsha": "b1abce7864744c3e21cb48d94fcc38cb7f74b2f4", "size": 3734, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "Azielh/FK", "max_stars_repo_head_hexsha": "ddb4d5c9eb8461f6f8d74bf73b1d8a133115e9e5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "Azielh/FK", "max_issues_repo_head_hexsha": "ddb4d5c9eb8461f6f8d74bf73b1d8a133115e9e5", "max_issues_repo_licenses": ["Apache-2.0"], "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": "Azielh/FK", "max_forks_repo_head_hexsha": "ddb4d5c9eb8461f6f8d74bf73b1d8a133115e9e5", "max_forks_repo_licenses": ["Apache-2.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.606557377, "max_line_length": 109, "alphanum_fraction": 0.4935725763, "num_tokens": 1182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065458, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7994111333350072}} {"text": "/**\n * @file Solution1DHO.cpp\n *\n * Calcul de l'équation schrödinger d'oscillateur harmonique à une dimension\n */\n#include \n#include \n#include \n#include \n#include \n#include \"HermitePolynomials.h\"\n#include \"Solution1DHO.h\"\n#include \"Utils.h\"\n\n/** Constructeur\n *\n * valeur m,w vaut 1 par défaut\n */\n\nSolution1DHO::Solution1DHO()\n{\n m=1;\n w=1;\n h=1;\n}\n\n/** Constructeur avec des valeurs données\n *\n * @param masse\n * @param pulsation\n */\n\nSolution1DHO::Solution1DHO(double masse, double pulsation)\n{\n m=masse;\n w=pulsation;\n}\n\n/** Initialisation des constantes\n *\n * Cette fonction permet d'initialiser les constantes\n *\n * @param m masse\n * @param w pulsation de l'onde\n *\n * @return rien\n */\nvoid Solution1DHO::setConstData(double m, double w)\n{\n this->w = w;\n this->m = m;\n}\n\n/** Calcul de la fonction d'onde Psi\n*\n* Cette fonction a pour but de calculer la fonction Psi solution de l'équation de Schrödinger 1D-HO.\n*\n* @param n\n* @param Z\n*\n* @return le résultat de la solution de 1D-HO Pn(z)\n*/\narma::mat Solution1DHO::solution(int n, arma::mat Z)\n{\n double f1;\n double f2;\n arma::mat f3;\n arma::mat res;\n\n f1 = (1/std::sqrt(std::exp(n * std::log(2)) * Utils::fac(n)));\n f2 = std::sqrt(std::sqrt(m * w / M_PI / h));\n f3 = arma::exp(-(m * w * (Z % Z) / 2 / h));\n\n res = f1 * f2 * (f3 % HermitePolynomials::calculateHermite(n, std::sqrt(m * w / h) * Z));\n\n return res;\n}\n\n/** Stockage des valeurs de la fonction d'onde\n*\n* Cette fonction a pour but de stocker les valeurs de la fonction d'onde dans un fichier plot.txt\n*\n* @param n\n* @param Z\n*\n* @return rien\n*/\nvoid Solution1DHO::solutionToFile(int n, arma::mat Z)\n{\n arma::mat res = Solution1DHO::solution(n,Z);\n\n std::ofstream out(\"plot.txt\");\n if (out.is_open())\n {\n out << Z;\n out << res << std::endl;\n out.close();\n }\n std::cout << \"La solution de l'équation est stockée dans plot.txt\" << std::endl;\n\n}\n\n/** Tracer le graphe de la fonction d'onde Psi\n*\n* Cette fonction a pour but de tracer le graph de la fonction d'onde Psi\n* avec python par appel système.\n*\n* @return rien\n*/\nvoid Solution1DHO::drawSolution()\n{\n std::cout << \"Tracer du graphe avec les données de plot.txt! \" << std::endl;\n system(\"python plot.py\");\n}\n\n/**\n * Calcul de l'énergie\n *\n * Cette fonction a pout but de calculer l'énergie en connaissant la fonction d'onde pour vérifier qu'elle est constante.\n * # Equation de Schrödinger\n * \\f[\\left(\\frac{\\hat{p}_{(z)}^2}{2m} + \\frac{1}{2}m\\omega^2\\hat{z}^2\\right)\\psi_n = E_n\\psi_n.\\f]\n *\n * @param n mode de l'énergie\n * @param a limite supérieur de Z\n * @param b limite inférieur de Z\n * @param N nombre de points z à caculer\n *\n *\n *\n * @retval E un vecteur contenant les valeurs des énergies pour N points.\n */\narma::mat Solution1DHO::energy(int n, double a, double b, int N)\n{\n double pas = (b-a)/N;\n arma::mat Z = arma::linspace(a,b+2*pas,N+2);\n arma::mat Psi = Solution1DHO::solution(n,Z);\n arma::mat dPsi = Utils::derivative(Psi.rows(0,N), Psi.rows(1,N+1),Z.rows(0,N), Z.rows(1,N+1));\n arma::mat d2Psi = Utils::derivative(dPsi.rows(0,N-1), dPsi.rows(1,N), Z.rows(0,N-1), Z.rows(1,N));\n\n arma::mat ZN = Z.rows(0,N-1);\n arma::mat PsiN = Psi.rows(0,N-1);\n arma::mat E;\n E = -1 * h * h * d2Psi / (2 * m * PsiN) + m * w * w * ZN % ZN / 2;\n return E;\n}\n", "meta": {"hexsha": "1be316d7a95877f579bb136b5b9f01ee75190fd8", "size": 3402, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Solution1DHO.cpp", "max_stars_repo_name": "DinghaoLI/SchrodingerEquation", "max_stars_repo_head_hexsha": "1dc139b5ca33506e28de7e4a9c966e86f3c2078b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Solution1DHO.cpp", "max_issues_repo_name": "DinghaoLI/SchrodingerEquation", "max_issues_repo_head_hexsha": "1dc139b5ca33506e28de7e4a9c966e86f3c2078b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Solution1DHO.cpp", "max_forks_repo_name": "DinghaoLI/SchrodingerEquation", "max_forks_repo_head_hexsha": "1dc139b5ca33506e28de7e4a9c966e86f3c2078b", "max_forks_repo_licenses": ["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.301369863, "max_line_length": 121, "alphanum_fraction": 0.6278659612, "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591977, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7994111220629886}} {"text": "/*\r\n######################################################\r\nIntroduction to Criptography - 2021 - Homework5\r\nLast modification (12-May-2021)\r\n\r\nAuthor: Gaina Robert-Adrian\r\nContact: gainarobertadrian@gmail.com\r\n\r\nRSA system:\r\n1. RSA encryption+decryption\r\n2. RSA CRT decryption\r\n3. Wiener attack\r\n######################################################\r\n\r\nResources:\r\n1. https://profs.info.uaic.ro/~tr/tr03-02.pdf\r\n2. https://profs.info.uaic.ro/~siftene/Wiener.pdf\r\n3. https://libntl.org/ (Big number library)\r\n4. http://cacr.uwaterloo.ca/hac/about/chap8.pdf\r\n*/\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\nusing namespace std;\r\nusing namespace std::chrono;\r\nusing namespace NTL;\r\n\r\nZZ encrypted_number;\r\n\r\nclass RSA {\r\nprivate:\r\n\tZZ p, q, phi, d;\r\n\r\n\tstring numberToText(ZZ number) {\r\n\t\tZZ copy = number;\r\n\t\tstring ans = \"\";\r\n\t\twhile (copy > 0) {\r\n\t\t\tchar chr = 0;\r\n\t\t\tint aux = 1;\r\n\t\t\tfor (int i = 0; i < 8; ++i) {\r\n\t\t\t\tchr += (copy % 2) * aux;\r\n\t\t\t\tcopy /= 2;\r\n\t\t\t\taux *= 2;\r\n\t\t\t}\r\n\t\t\tans.push_back(chr);\r\n\t\t}\r\n\t\treverse(ans.begin(), ans.end());\r\n\t\treturn ans;\r\n\t}\r\n\r\n\tZZ textToNumber(string text) {\r\n\t\tZZ number(0);\r\n\t\t/*Transform the string into a number*/\r\n\t\tfor (int i = 0; i < text.length(); ++i) {\r\n\t\t\tfor (int j = 7; j >= 0; --j) {\r\n\t\t\t\tif ((text[i] >> j) & 1) {\r\n\t\t\t\t\tnumber *= 2;\r\n\t\t\t\t\t++number;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tnumber *= 2;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn number;\r\n\t}\r\n\r\n\tvector continuedFractionExpansion(ZZ n, ZZ e) {\r\n\t\tvector ans;\r\n\t\tZZ r;\r\n\t\twhile (n != 0) {\r\n\t\t\tans.push_back(e / n);\r\n\t\t\tr = e % n;\r\n\t\t\te = n;\r\n\t\t\tn = r;\r\n\t\t}\r\n\t\treturn ans;\r\n\t}\r\n\r\n\tvector> getConvergents(vector fractionExpansion) {\r\n\t\tvector> ans;\r\n\t\tZZ alpha = fractionExpansion[0];\r\n\t\tZZ beta(1);\r\n\t\t\r\n\t\tans.push_back(make_pair(alpha, beta));\r\n\r\n\t\talpha = fractionExpansion[0] * fractionExpansion[1] + 1;\r\n\t\tbeta = fractionExpansion[1];\r\n\t\tans.push_back(make_pair(alpha, beta));\r\n\r\n\t\tfor (int i = 2; i < fractionExpansion.size(); ++i) {\r\n\t\t\talpha = fractionExpansion[i] * alpha + ans[i - 2].first;\r\n\t\t\tbeta = fractionExpansion[i] * beta + ans[i - 2].second;\r\n\t\t\tans.push_back(make_pair(alpha, beta));\r\n\t\t}\r\n\t\treturn ans;\r\n\t}\r\n\r\npublic:\r\n\tZZ e, n;\r\n\r\n\tZZ getP() {\r\n\t\treturn p;\r\n\t}\r\n\r\n\tZZ getQ() {\r\n\t\treturn q;\r\n\t}\r\n\r\n\tZZ getD() {\r\n\t\treturn d;\r\n\t}\r\n\r\n\tpair generateKeys(int length) {\r\n\t\tGenPrime(p, length);\r\n\t\tGenPrime(q, length);\r\n\t\t\r\n\t\tn = p * q;\r\n\t\tphi = (p - 1) * (q - 1);\r\n\r\n\t\te = 2;\r\n\t\twhile (GCD(e, phi) != 1) {\r\n\t\t\t//GenPrime(e, length - length / 2);\r\n\t\t\tGenPrime(e, 32);\r\n\t\t}\r\n\r\n\t\tInvMod(d, e, phi);\r\n\r\n\t\tcout << \"p:\" << p << \"\\n\\n\";\r\n\t\tcout << \"q:\" << q << \"\\n\\n\";\r\n\t\tcout << \"n:\" << n << \"\\n\\n\";\r\n\t\tcout << \"phi:\" << phi << \"\\n\\n\";\r\n\t\tcout << \"e:\" << e << \"\\n\\n\";\r\n\t\tcout << \"d:\" << d << \"\\n\\n\";\r\n\r\n\t\treturn make_pair(e, n);\r\n\t}\r\n\r\n\tstring encrypt(string text,pair public_key) {\r\n\t\tZZ number = textToNumber(text);\r\n\r\n\t\tcout <<\"[encrypt]Converted number:\"<< number << \"\\n\";\r\n\t\tcout << \"[encrypt]PublicKey: <\" << public_key.first << \",\" << public_key.second << \">\\n\";\r\n\r\n\t\tZZ result = PowerMod(number, public_key.first, public_key.second);\r\n\t\tencrypted_number = result;\r\n\r\n\t\tcout <<\"[encrypt]Encrypted number: \"<< result<< \"\\n\";\r\n\t\tstring cypertext = numberToText(result);\r\n\t\tcout << \"[encrypt]Encrypted text: \" << cypertext << \"\\n\\n\";\r\n\r\n\t\treturn cypertext;\r\n\t}\r\n\r\n\tstring decrypt(string encrypted) {\r\n\t\tauto start = high_resolution_clock::now();\r\n\t\tZZ decrypted = PowerMod(textToNumber(encrypted), d, n);\r\n\t\tauto stop = high_resolution_clock::now();\r\n\t\tstring plaintext = numberToText(decrypted);\r\n\t\tcout << \"[decrypt]Decrypted number: \" << decrypted << \"\\n\";\r\n\t\tcout << \"[decrypt]Decrypted text: \" << plaintext << \"\\n\";\r\n\t\tauto duration = duration_cast(stop - start);\r\n\r\n\t\tcout << \"[decrypt]Time taken by standard decryption: \"\r\n\t\t\t<< duration.count() << \" microseconds\" << \"\\n\\n\";\r\n\t\treturn plaintext;\r\n\t}\r\n\r\n\tstring decryptCRT(ZZ n, ZZ p, ZZ q, ZZ d, ZZ number) {\r\n\t\tif (p > q) {\r\n\t\t\tswap(p, q);\r\n\t\t}\r\n\t\tcout << \"[decryptCRT]Number to be decrypted:\" << number << '\\n';\r\n\t\tauto start = high_resolution_clock::now();\r\n\t\tZZ n1 = d % (p - 1);\r\n\t\tZZ n2 = d % (q - 1);\r\n\t\tZZ inv = InvMod(p, q);\r\n\r\n\t\tZZ x1 = PowerMod(number % p, n1, p);\r\n\t\tZZ x2 = PowerMod(number % q, n2, q);\r\n\t\tZZ mul = (x2 - x1) * (inv % q) % q;\r\n\t\tZZ x = x1 + p * mul;\r\n\t\tauto stop = high_resolution_clock::now();\r\n\t\tstring ans = numberToText(x);\r\n\t\tauto duration = duration_cast(stop - start);\r\n\r\n\t\tcout << \"[decryptCRT]Decrypted number:\" << x << '\\n';\r\n\t\tcout << \"[decryptCRT]Decrypted text:\" << ans << \"\\n\";\r\n\t\tcout << \"[decryptCRT]Time taken by CRT decryption: \"\r\n\t\t\t<< duration.count() << \" microseconds\" << \"\\n\\n\";\r\n\t\treturn ans;\r\n\t}\r\n\r\n\tpair generateWienerKeys() {\r\n\t\tZZ p, q;\r\n\t\twhile (true) {\r\n\t\t\tGenPrime(p, 512);\r\n\t\t\tGenPrime(q, 512);\r\n\t\t\tif (p < q) {\r\n\t\t\t\tswap(p, q);\r\n\t\t\t}\r\n\t\t\tif (q < p && p < 2 * q) {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcout << \"I\" << '\\n';\r\n\t\t}\r\n\t\tZZ n = p * q;\r\n\t\tZZ phi = (p - 1) * (q - 1);\r\n\r\n\t\tZZ d;\r\n\t\twhile (true) {\r\n\t\t\tGenPrime(d, 32);\r\n\t\t\tif (d < SqrRoot(SqrRoot(n)) / 3)\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t\tZZ e;\r\n\t\tInvMod(e, d, phi);\r\n\r\n\t\tcout << \"P:\" << p << \"\\n\\n\";\r\n\t\tcout << \"Q:\" << q << \"\\n\\n\";\r\n\t\tcout << \"N:\" << n << \"\\n\\n\";\r\n\t\tcout << \"Phi:\" << phi << \"\\n\\n\";\r\n\t\tcout << \"E:\" << e << \"\\n\\n\";\r\n\t\tcout << \"D:\" << d << \"\\n\\n\";\r\n\r\n\t\treturn make_pair(e, n);\r\n\t\t\r\n\t}\r\n\r\n\tvoid wienerAttack(ZZ n, ZZ e) {\r\n\t\tvector fractionExpansion = continuedFractionExpansion(n, e);\r\n\t\tvector> convergents = getConvergents(fractionExpansion);\r\n\r\n\t\tZZ d;\r\n\r\n\t\tfor (auto fraction : convergents) {\r\n\t\t\tif (fraction.first == 0) { // If alpha is 0 alpha*beta can't be n\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\tif ((e * fraction.second - 1) % fraction.first != 0) { //e*d-1=l*phi(n) === (e*d)-1 mod l = 0 \r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tZZ phi = (e * fraction.second - 1) / fraction.first; //(e*d-1)/l=phi(n)\r\n\t\t\t/* Equation of rank 2 is: y^2 - (n+1-phi(n)*y - n = 0 */\r\n\t\t\tZZ a(1);\r\n\t\t\tZZ b = (n + 1 - phi) * -1;\r\n\t\t\tZZ c = n;\r\n\r\n\t\t\tZZ delta = b * b - 4 * a * c;\r\n\t\t\tif (delta <= 0) { \r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\tZZ sqrtDelta;\r\n\t\t\tSqrRoot(sqrtDelta, delta);\r\n\t\t\tif (sqrtDelta * sqrtDelta != delta) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tb *= -1;\r\n\t\t\tZZ x1 = (b + sqrtDelta) / (2 * a);\r\n\t\t\tZZ x2 = (b - sqrtDelta) / (2 * a);\r\n\t\t\tif (x1 * x2 == n) {\r\n\t\t\t\tcout <<\"D=\"<< fraction.second<< \" found\\n\";;\r\n\t\t\t\tInvMod(d, e, phi);\r\n\t\t\t\tcout << \"Real D=\" << d << \"\\n\";\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n};\r\n\r\nint main() {\r\n\tRSA instance = RSA();\r\n\tcout << \"~~~~~~~~~~~~~~~~~~~~~~Key generation start~~~~~~~~~~~~~~~~~~~~~\\n\";\r\n\tpair key=instance.generateKeys(512);\r\n\tcout << \"~~~~~~~~~~~~~~~~~~~~~~Key generation stop~~~~~~~~~~~~~~~~~~~~~\\n\\n\\n\";\r\n\r\n\tstring text = \"plaintext_example\";\r\n\tcout << \"~~~~~~~~~~~~~~~~~~~~~~Encrypt start~~~~~~~~~~~~~~~~~~~~~\\n\";\r\n\tstring cypertext=instance.encrypt(text,key);\r\n\tcout << \"~~~~~~~~~~~~~~~~~~~~~~Encrypt stop~~~~~~~~~~~~~~~~~~~~~\\n\\n\\n\";\r\n\r\n\tcout << \"~~~~~~~~~~~~~~~~~~~~~~Decrypt start~~~~~~~~~~~~~~~~~~~~~\\n\";\r\n\tstring plaintext = instance.decrypt(cypertext);\r\n\tstring plaintext2 = instance.decryptCRT(instance.n, instance.getP(), instance.getQ(), instance.getD(), encrypted_number);\r\n\tcout << \"~~~~~~~~~~~~~~~~~~~~~~Decrypt stop~~~~~~~~~~~~~~~~~~~~~\\n\\n\\n\";\r\n\tcout << \"C: \" << cypertext << \"\\nP: \" << plaintext <<\"\\nP2: \"<\n#include \n#include \"Vector.h\"\n#include \n\nusing namespace std;\n\nint target = 1000;\n\nint main(int argc, char** argv) {\n // Lazy primes generation, since the amount we need is so low.\n Vector primes;\n primes.insertBack(2);\n for (int i = primes[0]; i < target; i++) {\n bool foundFactor = false;\n for (int j = 0; j < primes.length(); j++) {\n cout << i << \", \" << j << endl;\n if (i % primes[j] == 0) {\n foundFactor = true;\n break;\n }\n }\n if (!foundFactor) {\n cout << \"No factors for \" << i << endl;\n primes.insertBack(i);\n }\n }\n\n int highestPeriodIndex;\n int highestPeriod = 0;\n\n for (int i = 0; i < primes.length(); i++) {\n int prime = primes[i];\n if (prime == 2 || prime == 5) {\n // Special case: according to number theory, the rule doesn't apply to\n // these two, probably because they're both factors of 10.\n continue;\n }\n int a = 10;\n boost::multiprecision::mpz_int ak = a;\n int k = 1;\n while (ak % prime != 1) {\n ak *= a;\n k++;\n }\n if (k > highestPeriod) {\n highestPeriod = k;\n highestPeriodIndex = i;\n }\n }\n\n cout << \"Number from 1 to \" << target << \" with highest number of repeating digits: \"\n << primes[highestPeriodIndex] << \" with period of \" << highestPeriod << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "55f30c51c007d7f69c7e8dbfe955e5ba5b5734ec", "size": 1981, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "26.cpp", "max_stars_repo_name": "DouglasSherk/project-euler", "max_stars_repo_head_hexsha": "f3b188b199ff31671c6d7683b15675be7484c5b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "26.cpp", "max_issues_repo_name": "DouglasSherk/project-euler", "max_issues_repo_head_hexsha": "f3b188b199ff31671c6d7683b15675be7484c5b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "26.cpp", "max_forks_repo_name": "DouglasSherk/project-euler", "max_forks_repo_head_hexsha": "f3b188b199ff31671c6d7683b15675be7484c5b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1369863014, "max_line_length": 87, "alphanum_fraction": 0.6325088339, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338090839607, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7991721326574651}} {"text": "// gauss_jordan.cpp : example program comparing float vs posit matrix inversion algorithms\n//\n// Copyright (C) 2017-2019 Stillwater Supercomputing, Inc.\n//\n// This file is part of the HPR-BLAS project, which is released under an MIT Open Source license.\n\n//#include \n// Boost arbitrary precision floats\n#include \n\n// configure the posit number system behavior\n#define POSIT_ROUNDING_ERROR_FREE_IO_FORMAT 0\n// configure the HPR-BLAS behavior\n#define HPRBLAS_TRACE_ROUNDING_EVENTS 0\n#include \n#include \n// matrix generators\n#include \n#include \n\ntemplate\nvoid GenerateNumericalAnalysisTestCase(const std::string& header, unsigned N, bool verbose = false) {\n\tusing namespace std;\n\tusing namespace mtl;\n\tusing namespace sw::unum;\n\tusing namespace sw::hprblas;\n\n\tstd::cout << \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\" << header << std::endl;\n\tusing Vector = mtl::vec::dense_vector;\n\tusing Matrix = mtl::mat::dense2D;\n\n\tMatrix H(N, N);\n\tGenerateHilbertMatrix(H, false);\n\tMatrix Hinv = GaussJordanInversion(H);\n\tMatrix Href(N, N);\n\tGenerateHilbertMatrixInverse(Href);\n\tMatrix I(N, N); // H * Hinv should yield the identity matrix\n\t// TODO: this is not clear that for posits this would be a fused matrix multiply\n\tmatmul(I, H, Hinv);\n\n\tif (verbose) {\n\t\tprintMatrix(cout, \"Hilbert matrix order 5\", H);\n\t\tprintMatrix(cout, \"Hilbert inverse\", Hinv);\n\n\t\tprintMatrix(cout, \"Hilbert inverse reference\", Href);\n\n\t\tprintMatrix(cout, \"H * H^-1 => I\", I);\n\t}\n\n\t// calculate the numerical error caused by the linear algebra computation\n\tVector e(N), eprime(N), eabsolute(N), erelative(N);\n\te = Scalar(1);\n\t// TODO: it is not clear that for posits this would be a fused matrix-vector operation\n\tmatvec(eprime, I, e);\n\tprintVector(cout, \"reference vector\", e);\n\tprintVector(cout, \"error vector\", eprime);\n\t// absolute error\n\teabsolute = e - eprime;\n\tprintVector(cout, \"absolute error vector\", eabsolute);\n\tcout << \"L1 norm \" << hex_format(l1_norm(eabsolute)) << \" \" << l1_norm(eabsolute) << endl;\n\tcout << \"L2 norm \" << hex_format(l2_norm(eabsolute)) << \" \" << l2_norm(eabsolute) << endl;\n\tcout << \"Linf norm \" << hex_format(linf_norm(eabsolute)) << \" \" << linf_norm(eabsolute) << endl;\n\n\t// relative error\n\tcout << \"relative error\\n\";\n\tScalar relative_error;\n\trelative_error = l1_norm(eabsolute) / l1_norm(e);\n\tcout << \"L1 norm \" << hex_format(relative_error) << \" \" << relative_error << endl;\n\trelative_error = l2_norm(eabsolute) / l2_norm(e);\n\tcout << \"L2 norm \" << hex_format(relative_error) << \" \" << relative_error << endl;\n\trelative_error = linf_norm(eabsolute) / linf_norm(e);\n\tcout << \"Linf norm \" << hex_format(relative_error) << \" \" << relative_error << endl;\n\n\t// error volume\n\tcout << \"error bounding box volume\\n\";\n\tcout << \"Measured in Euclidean distance : \" << error_volume(linf_norm(eabsolute), N, false) << endl;\n\tcout << \"Measured in ULPs : \" << error_volume(linf_norm(eabsolute), N, true) << \" ulps^\" << N << endl;\n\tScalar ulp = numeric_limits::epsilon();\n\tcout << \"L-infinitiy norm measured in ULPs : \" << linf_norm(eabsolute) / ulp << \" ulps\" << endl;\n}\n\nint main(int argc, char** argv)\ntry {\n\tusing namespace std;\n\tusing namespace mtl;\n\tusing namespace sw::unum;\n\tusing namespace sw::hprblas;\n\tusing namespace boost::multiprecision;\n\n\tusing sp = boost::multiprecision::cpp_bin_float_single;\n\tusing dp = boost::multiprecision::cpp_bin_float_double;\n\tusing qp = boost::multiprecision::cpp_bin_float_quad;\n\n\n\tunsigned N = 5; \n\tGenerateNumericalAnalysisTestCase< posit<32, 2> >(\"posit<32,2>\", N);\n\tcout << endl;\n\tGenerateNumericalAnalysisTestCase< float >(\"IEEE single precision\", N);\n\tcout << endl;\n\tGenerateNumericalAnalysisTestCase< posit<64, 3> >(\"posit<64,3>\", N);\n\tcout << endl;\n\tGenerateNumericalAnalysisTestCase< double >(\"IEEE double precision\", N);\n\tcout << endl;\n\tGenerateNumericalAnalysisTestCase< posit<128, 4> >(\"posit<128,4>\", N);\n\tcout << endl;\n\tGenerateNumericalAnalysisTestCase< qp >(\"IEEE quad precision\", N);\n\n\treturn EXIT_SUCCESS;\n}\ncatch (char const* msg) {\n\tstd::cerr << msg << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_arithmetic_exception& err) {\n\tstd::cerr << \"Uncaught posit arithmetic exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const quire_exception& err) {\n\tstd::cerr << \"Uncaught quire exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_internal_exception& err) {\n\tstd::cerr << \"Uncaught posit internal exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (std::runtime_error& err) {\n\tstd::cerr << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (...) {\n\tstd::cerr << \"Caught unknown exception\" << std::endl;\n\treturn EXIT_FAILURE;\n}\n", "meta": {"hexsha": "898d4eb174fa1e0d3cafdd24cde4cdbc8eaa46a9", "size": 4887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "solvers/gauss_jordan.cpp", "max_stars_repo_name": "fossabot/hpr-blas", "max_stars_repo_head_hexsha": "dad4656f556ea62abddbf3ddbb712d6b77fe7e91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "solvers/gauss_jordan.cpp", "max_issues_repo_name": "fossabot/hpr-blas", "max_issues_repo_head_hexsha": "dad4656f556ea62abddbf3ddbb712d6b77fe7e91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solvers/gauss_jordan.cpp", "max_forks_repo_name": "fossabot/hpr-blas", "max_forks_repo_head_hexsha": "dad4656f556ea62abddbf3ddbb712d6b77fe7e91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4701492537, "max_line_length": 120, "alphanum_fraction": 0.6957233477, "num_tokens": 1295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.8688267745399466, "lm_q1q2_score": 0.799010048352452}} {"text": "#include \r\n#include \r\n#include \r\n#include \"SeaWaves.h\"\r\n\r\n\r\nnamespace Upp {\r\n\r\nusing namespace Eigen;\r\n\r\ndouble SeaWaves::rho = 1024;\r\ndouble SeaWaves::g = 9.81;\r\n\r\ndouble SeaWaves::WaveNumber(double T, double h, bool exact) {\r\n\tdouble y = 4*M_PI*M_PI*h/g/(T*T);\r\n\tdouble k1 = 1 + 0.6666666666*y + 0.3555555555*pow(y,2) + 0.1608465608*pow(y,3) \r\n\t\t\t\t+ 0.0632098765*pow(y,4) + 0.0217540484*pow(y,5) + 0.0065407983*pow(y,6);\r\n\tdouble k = sqrt((y*y + y/k1))/h;\r\n\t\r\n\tif (!exact)\r\n\t\treturn k;\r\n\t\r\n\tdouble w = 2*M_PI/T;\r\n\t\r\n\tVectorXd x(1);\r\n\tx[0] = k;\r\n\tif (SolveNonLinearEquations(x, [&](const VectorXd &x, VectorXd &residual)->int {\r\n\t\tresidual[0] = w*w - g*k*tanh(x[0]*h);\r\n\t\treturn 0;\r\n\t}))\r\n\t\treturn x[0];\r\n\r\n\treturn -1;\r\n}\r\n\r\nSeaWaves::SEA_TYPE SeaWaves::GetSeaType(double T, double h) {\r\n double h_L = h/WaveLength(T, h);\r\n\tif (h_L < 1./20)\r\n\t\treturn SHALLOW;\r\n\telse if (h_L < 1./2)\r\n\t\treturn INTERMEDIATE;\r\n\treturn DEEP;\r\n}\r\n\r\ndouble SeaWaves::WaveLength(double T, double h) \t{return 2*M_PI/WaveNumber(T, h);}\r\n\r\ndouble SeaWaves::Celerity(double T, double h) \t \t{return WaveLength(T, h)/T;}\r\n\r\ndouble SeaWaves::GroupCelerity(double T, double h) {\r\n double k = WaveNumber(T, h);\r\n double L = 2*M_PI/k;\t\t\t\r\n double c = L/T; \t\r\n double n = 0.5*(1 + 2*k*h/sinh(2*k*h)); \r\n return c*n; \r\n}\r\n\r\ndouble SeaWaves::Power(double Te, double Hs, double h) {\r\n\tdouble k = WaveNumber(Te, h);\r\n double L = 2*M_PI/k;\t\t\t\r\n double c = L/Te; \t\r\n double n = 0.5*(1 + 2*k*h/sinh(2*k*h)); \r\n double Cg = c*n; \r\n double E = 1/16.*rho*g*Hs*Hs;\t\r\n\treturn E*Cg/1000.; \t\r\n}\r\n\r\ndouble SeaWaves::JONSWAP_Spectrum(double Hm0, double Tp, double gamma, double freq) {\r\n\tdouble sigma_f = freq <= 1/Tp ? 0.07 : 0.09;\t \r\n\tdouble beta = 0.0624/(0.230 + 0.0336*gamma - 0.185/(1.9 + gamma))*(1.094 - 0.01915*log(gamma));\r\n\t\t\r\n\treturn beta*Hm0*Hm0*pow(Tp,-4)*pow(freq, -5)*exp(-5./4.*pow(Tp*freq, -4)) * pow(gamma, exp(-pow((Tp*freq - 1), 2)/(2*sigma_f*sigma_f)));\t\r\n}\r\n\r\nbool SeaWaves::JONSWAP_Spectrum_test(double Hm0, double Tp, double gamma) {\r\n\tif ((Tp > 5*sqrt(Hm0)) || (Tp < 3.6*sqrt(Hm0)))\r\n\t\treturn false;\r\n\tif (gamma > 7 || gamma < 1) \r\n\t\treturn false;\r\n\treturn true;\r\n}\r\n\r\nbool SeaWaves::Init(double Tp, double Hs, double dirM, double h, int nd, int nf, double gamma, \r\n\t\t\t\t\tdouble disp_ang, int seed, double fmin, double fmax) {\r\n\tif(!(Tp > 0 && nd > 0 && nf > 0 && gamma >= 1))\r\n\t\treturn false;\r\n\t\r\n\tthis->Tp = Tp; \t\t\t\t\r\n\tthis->dirM = dirM; \t\t\t\r\n\tthis->Hs = Hs; \t\r\n\tthis->h = h; \r\n\tthis->nd = nd; \t\t\t\t\r\n\tthis->nf = nf = nf/nd;\t\r\n\r\n\tfrecs.resize(nf);\r\n\tk_f.resize(nf);\r\n\tdirs.resize(nd);\r\n\tamp_fd.resize(nd, nf);\r\n\tfi_fd.resize(nd, nf);\r\n\r\n\tdouble fp = 1/Tp; \r\n\tif (nf > 1) {\r\n\t\tif (fmin < 0)\r\n\t\t\tfmin = 0.25/Tp;\r\n\t\telse if (fmin > fp)\r\n\t\t\treturn false;\r\n\t\tif (fmax < 0)\r\n\t\t\tfmax = 4/Tp; \r\n\t\telse if (fmax < fp)\r\n\t\t\treturn false;\r\n\t} else\r\n\t\tfmin = fmax = fp;\r\n\t\r\n\tdf = 1;\r\n\tif (nf > 1)\r\n\t\tdf = (fmax-fmin)/(nf - 1);\r\n\t\r\n\tfor(int f = 0; f < nf; f++) {\r\n\t\tint n = f + 1;\r\n\t frecs[f] = fmin + (n - 1)*df;\r\n\t k_f[f] = WaveNumber(1/frecs[f], h); \r\n\t}\r\n \r\n\tBuffer Sf_f(nf);\r\n\t\r\n\tif (nf > 1) {\r\n\t\tdouble beta = 0.0624/(0.230 + 0.0336*gamma - 0.185*(pow(1.9 + gamma, -1)))*(1.094 - 0.01915*log(gamma));\r\n\t\tfor(int f = 0; f < nf; f++) {\r\n\t\t\tdouble sigma_f;\r\n\t\t\tif(frecs[f] <= fp)\r\n\t\t sigma_f = 0.07;\r\n\t\t\telse\r\n\t\t\t\tsigma_f = 0.09;\t \r\n\t\r\n\t\t\tSf_f[f] = beta*pow(Hs, 2)*pow(Tp,-4)*pow(frecs[f], -5)*exp(-1.25*pow(Tp*frecs[f], -4)) \r\n\t\t\t\t\t\t *pow(gamma, exp(-pow((Tp*frecs[f]-1), 2)/2/pow(sigma_f, 2)));\r\n\t\t}\r\n\t} else \r\n\t\tSf_f[0] = 1/2.*pow(Hs/2., 2);\r\n\t\r\n\tif (nd > 1) {\r\n\t double dirmin = dirM - disp_ang; \t\r\n\t double dirmax = dirM + disp_ang; \t\r\n\t double dd = (dirmax - dirmin)/(nd-1);\r\n\t \r\n\t for (int d = 0; d < nd; ++d)\r\n\t dirs[d] = dirmin + d*dd; \r\n\r\n\t double L0 = g*Tp*Tp/2./M_PI; \r\n\t double per = Hs/L0; \t\t\t\t\t\t\t\t\r\n\t double Smax = pow(10, -1.2195*log10(per) - 0.5573); \r\n\t \r\n\t\tBuffer incdir_d(nd);\r\n\t\t\r\n\t\tfor (int d = 0; d < nd; ++d)\r\n\t\t\tincdir_d[d] = dirs[d] - dirM;\r\n\t\t\t\t\r\n\t\tfor (int f = 0; f < nf; f++) { \r\n\t\t\tdouble s_f;\r\n\t\t if (frecs[f] <= fp)\r\n\t\t s_f = pow((frecs[f]/fp), 5)*Smax;\r\n\t\t else\r\n\t\t s_f = pow((frecs[f]/fp), -2.5)*Smax; \r\n\t\t \r\n\t\t double G0_f = 0; \r\n\t\t for (int d = 0; d < nd; d++) \r\n\t\t G0_f += pow(cos(incdir_d[d]/2), 2*s_f)*dd;\r\n\t\t G0_f = 1/G0_f;\r\n\t\r\n\t \tfor (int d = 0; d < nd; d++) {\r\n\t\t double G_fd = G0_f*pow(cos(incdir_d[d]/2.), 2*s_f);\r\n\t\t double Sfd_fd = Sf_f[f]*G_fd;\r\n\t\t amp_fd(d, f) = sqrt(2*Sfd_fd*df*dd);\r\n\t\t }\r\n\t\t}\r\n\t} else {\r\n\t dirs[0] = dirM;\r\n\t for (int f = 0; f < nf; ++f)\r\n\t amp_fd(0, f) = sqrt(2*Sf_f[f]*df);\r\n\t}\r\n\t\t\r\n\tif (nf > 1) {\r\n\t\tif (IsNull(seed)) {\r\n\t\t\tstd::random_device rd;\r\n\t\t\tseed = rd();\r\n\t\t} \r\n\t\tstd::mt19937 random_engine(seed);\r\n\t\tstd::uniform_real_distribution random_distribution(-M_PI, M_PI);\r\n\t\tfor (int f = 0; f < nf; f++) \r\n\t\t for (int d = 0; d < nd; d++) \r\n\t\t\t\tfi_fd(d, f) = random_distribution(random_engine);\t\t\r\n\t} else {\r\n\t\tfor (int d = 0; d < nd; d++) \r\n\t\t\tfi_fd(d, 0) = 0;\r\n\t}\r\n\t\r\n\treturn true;\r\n}\r\n\r\nvoid SeaWaves::Calc(double x, double y, double z, double t) {\t\r\n\tASSERT(frecs.size() > 0);\r\n\t\r\n zSurf = dzSurf = vx = vy = vz = ax = ay = az = 0;\r\n\t\r\n\tp = -rho*g*z; \r\n\t\r\n\tfor (int f = 0; f < nf; f++) {\r\n \tfor (int d = 0; d < nd; d++) {\r\n \t\tdouble frec = frecs[f];\r\n \t\tdouble sindirsd = sin(dirs[d]);\r\n \t\tdouble cosdirsd = cos(dirs[d]);\r\n \t\tdouble aux = k_f[f]*cosdirsd*x + k_f[f]*sindirsd*y - 2*M_PI*frec*t + fi_fd(d, f);\r\n \t\tdouble auxcos = cos(aux);\r\n \t\tdouble auxsin = sin(aux);\r\n \t\t\r\n\t double AUXsl = amp_fd(d, f)*auxcos; \r\n zSurf += AUXsl;\r\n dzSurf += 2*M_PI*frec*amp_fd(d, f)*auxsin; \r\n\t \r\n\t double kp = cosh(k_f[f]*(h+z))/cosh(k_f[f]*h);\r\n\t double kp_sin = sinh(k_f[f]*(h+z))/cosh(k_f[f]*h);\r\n\t\r\n\t double AUXvh = g*amp_fd(d, f)*k_f[f]/(2*M_PI*frec)*kp*auxcos; \r\n\t vx += AUXvh*cosdirsd;\r\n\t vy += AUXvh*sindirsd;\r\n\t \r\n\t vz += g*amp_fd(d, f)*k_f[f]/(2*M_PI*frec)*kp_sin*auxsin;\r\n\t \r\n\t double AUXah = g*amp_fd(d, f)*pow((k_f[f]),2)/(2*M_PI*frec)*kp*auxsin;\r\n\t ax += AUXah*cosdirsd;\r\n\t ay += AUXah*sindirsd;\r\n\t \r\n\t az += -g*amp_fd(d, f)*pow((k_f[f]),2)/(2*M_PI*frec)*kp_sin*auxcos; \r\n\t \r\n\t \t\tp += rho*g*kp*AUXsl;\t\r\n \t}\r\n\t}\r\n}\r\n\r\ndouble SeaWaves::ZSurf(double x, double y, double z, double t) {\r\n\tASSERT(frecs.size() > 0);\r\n\t\r\n double zSurf = 0;\r\n\tfor (int f = 0; f < nf; f++) \r\n \tfor (int d = 0; d < nd; d++) \r\n\t zSurf += amp_fd(d, f)*cos(k_f[f]*cos(dirs[d])*x + k_f[f]*sin(dirs[d])*y \r\n\t \t\t\t\t\t\t - 2*M_PI*frecs[f]*t + fi_fd(d, f)); \r\n return zSurf;\r\n}\r\n\r\ndouble SeaWaves::Pressure(double x, double y, double z, double t) {\r\n\tASSERT(frecs.size() > 0);\r\n\t\r\n\tdouble p = -rho*g*z; \r\n\tfor (int f = 0; f < nf; f++) \r\n \tfor (int d = 0 ; d < nd; d++) {\r\n\t double KP = cosh(k_f[f]*(h+z))/cosh(k_f[f]*h);\t\r\n \t\tdouble AUXsl = amp_fd(d, f)*cos(k_f[f]*cos(dirs[d])*x + k_f[f]*sin(dirs[d])*y - 2*M_PI*frecs[f]*t + fi_fd(d, f)); \r\n \t\tp += rho*g*KP*AUXsl;\t\r\n \t}\r\n return p;\r\n}\r\n\r\n\r\n// DNV-RP-C205, page 34 \r\ndouble Te_fTp(double Tp, double gamma) \t {return Tp*(4.2 + gamma)/(5 + gamma);}\r\ndouble Tp_fTe(double Te, double gamma) \t {return Te*(5 + gamma)/(4.2 + gamma);}\r\ndouble gamma_fTp_Te(double Tp, double Te) {return (Te*5 - Tp*4.2)/(Tp - Te);}\r\ndouble Tp_fTm(double Tm, double gamma) \t {return Tm/(0.7303 + 0.04936*gamma - 0.006556*pow(gamma, 2) + 0.0003610*pow(gamma, 3));}\r\ndouble Tp_fTz(double Tz, double gamma) \t {return Tz/(0.6673 + 0.05037*gamma - 0.006230*pow(gamma, 2) + 0.0003341*pow(gamma, 3));}\r\n\t\r\ndouble gamma_fTp_Tz(double Tp, double Tz) {\r\n\tVectorXd x(1);\r\n\tx[0] = 5;\r\n\tif (SolveNonLinearEquations(x, [&](const VectorXd &x, VectorXd &residual)->int {\r\n\t\tdouble gamma = x[0];\r\n\t\tdouble gamma2 = gamma*gamma;\r\n\t\tresidual[0] = - Tz/Tp + 0.6673 + 0.05037*gamma - 0.006230*gamma2 + 0.0003341*gamma*gamma2;\r\n\t\treturn 0;\r\n\t}))\r\n\t\treturn x[0];\r\n\treturn -1;\r\n}\r\n\t\r\n}\t", "meta": {"hexsha": "8b33d2f04c6019d1442c126acb1966a54db58472", "size": 8325, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "STEM4U/SeaWaves.cpp", "max_stars_repo_name": "Libraries4U/STEM4U", "max_stars_repo_head_hexsha": "41472ce21420ff5bcf69577efefd924cf1e7c2cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "STEM4U/SeaWaves.cpp", "max_issues_repo_name": "Libraries4U/STEM4U", "max_issues_repo_head_hexsha": "41472ce21420ff5bcf69577efefd924cf1e7c2cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "STEM4U/SeaWaves.cpp", "max_forks_repo_name": "Libraries4U/STEM4U", "max_forks_repo_head_hexsha": "41472ce21420ff5bcf69577efefd924cf1e7c2cf", "max_forks_repo_licenses": ["Apache-2.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.3133802817, "max_line_length": 139, "alphanum_fraction": 0.5183183183, "num_tokens": 3122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133565584851, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7988992571182287}} {"text": "#include \n#include \n\n#include \"timer.h\"\n\n//! \\brief Use efficient implementation A*x = bb\n//! \\param[in] R Matrix is nxn and upper triangular\n//! \\param[in] v Vector is nx1\n//! \\param[in] u Vector is nx1\n//! \\param[in] bb vector is (n+1)x1 and is stacked (b, \\beta)^T =: b\n//! \\param[out] x solution A*bb = x\ntemplate \nvoid solvelse(const Matrix & R, const Vector & v, const Vector & u,\n const Vector & bb, Vector & x) {\n // Size of R, which is wize of u, v, and size of bb is n+1\n unsigned int n = R.rows();\n if( n != R.cols() || n != u.size() || n != v.size() || n+1 != bb.size() ) {\n // Size check, error if do not match\n std::cerr << \"Error: size mismatch!\" << std::endl;\n return;\n }\n \n // This gets the scalar type of the matrix\n typedef typename Matrix::Scalar Scalar; \n // Tell eigen R is triangular, we use the construct R.template to avoid compilation errors\n // cf. http://eigen.tuxfamily.org/dox-devel/TopicTemplateKeyword.html\n // here auto = const Eigen::TriangularView\n auto triR = R.template triangularView();\n \n // s is the Schur's complement and, in this case, is a scalar (and so is b_s)\n // snv = s^{-1}, b_s as in lecture notes\n // sinvbs = s^{-1}*b_s\n Scalar sinv = - 1. / u.dot(triR.solve(v));\n Scalar bs = (bb(n) - u.dot(triR.solve(bb.head(n))));\n Scalar sinvbs = sinv*bs;\n \n // Stack the vector (z, \\xi)^T =: x\n x = Vector::Zero(n+1);\n x << triR.solve(bb.head(n) - v*sinvbs), sinvbs;\n}\n\n//! \\brief Use Eigen's LU-solver to solve Ax = y\n//! \\param[in] R Matrix is nxn and upper triangular\n//! \\param[in] v Vector is nx1\n//! \\param[in] u Vector is nx1\n//! \\param[in] bb vector is (n+1)x1 and is stacked (b, \\beta)^T =: b\n//! \\param[out] x solution A*bb = x\ntemplate \nvoid solvelse_lu(const Matrix & R, const Vector & v, const Vector & u,\n const Vector & bb, Vector & x) {\n // Size of R, which is wize of u, v, and size of bb is n+1\n unsigned int n = R.rows();\n if( n != R.cols() && n != u.size() && n != v.size() && n+1 != bb.size() ) {\n // Size check, error if do not match\n std::cerr << \"Error: size mismatch!\" << std::endl;\n return;\n }\n \n Matrix A(n+1,n+1);\n A << R, v, u.transpose(), 0;\n \n x = A.partialPivLu().solve(bb);\n}\n\nint main() {\n // Bunch of random vectors/matrices\n int n = 9;\n Eigen::MatrixXd R = Eigen::MatrixXd::Random(n,n).triangularView();\n Eigen::VectorXd v = Eigen::VectorXd::Random(n);\n Eigen::VectorXd u = Eigen::VectorXd::Random(n);\n Eigen::VectorXd bb = Eigen::VectorXd::Random(n+1);\n Eigen::VectorXd x;\n \n // Check that answer is correct\n std::cout << \"*** Check correctness of Block Gauss implementation\" << std::endl;\n solvelse(R, v, u, bb, x);\n std::cout << \"Block Gauss:\" << std::endl << x << std::endl;\n // Compare with eigen partial pivot LU-solve\n solvelse_lu(R, v, u, bb, x);\n std::cout << \"Eigen LU:\" << std::endl << x << std::endl;\n \n // Compute runtime of different implementations of kron\n std::cout << \"*** Runtime comparisons of Block Gauss implementation VS Eigen LU\" << std::endl;\n unsigned int repeats = 3;\n timer<> tm_own, tm_eigen_lu;\n \n for(unsigned int p = 2; p <= 10; p++) {\n tm_own.reset();\n tm_eigen_lu.reset();\n for(unsigned int r = 0; r < repeats; ++r) {\n unsigned int M = pow(2,p);\n R = Eigen::MatrixXd::Random(M,M).triangularView(); // We will use only upper triangular part\n v = Eigen::VectorXd::Random(M);\n u = Eigen::VectorXd::Random(M);\n bb = Eigen::VectorXd::Random(M+1);\n \n tm_own.start();\n solvelse(R, v, u, bb, x);\n tm_own.stop();\n \n tm_eigen_lu.start();\n solvelse_lu(R, v, u, bb, x);\n tm_eigen_lu.stop();\n }\n \n std::cout << \"Own implementation took: \" << tm_own.min().count() / 1000000. << \" ms\" << std::endl;\n std::cout << \"Eigen solver took: \" << tm_eigen_lu.min().count() / 1000000. << \" ms\" << std::endl;\n }\n}\n", "meta": {"hexsha": "10a3a49a8cda4512986f05311582a63d0c0f0610", "size": 4293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/solutions/solution_2/block_lu_decomp.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/solutions/solution_2/block_lu_decomp.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/solutions/solution_2/block_lu_decomp.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0272727273, "max_line_length": 118, "alphanum_fraction": 0.5679012346, "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206818021529, "lm_q2_score": 0.8856314738181875, "lm_q1q2_score": 0.7987693426915452}} {"text": "// Author: Haralambi Todorov \n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace boost::multiprecision;\n\nstruct fraction {\n int256_t n; // numerator\n int256_t d; // denominator\n fraction(const int256_t &_n,\n const int256_t &_d) : n(_n), d(_d) {}\n};\n\nfraction add_int_to_frac(const int256_t &i,\n const fraction &f) {\n return fraction(i * f.d + f.n, f.d);\n}\n\nfraction int_over_frac(const int256_t &i,\n const fraction &f) {\n return fraction(f.d * i, f.n);\n}\n\nstd::vector e_sequence(const size_t &n) {\n std::vector res;\n res.push_back(2);\n size_t i = 1;\n while (res.size() < n) {\n if ((res.size() + 1) % 3 == false) {\n res.push_back(2 * i);\n i++;\n } else {\n res.push_back(1);\n }\n }\n return res;\n}\n\nint256_t sum_digits(const int256_t &i) {\n int256_t sum = i % 10;\n int256_t _i = i / 10;\n while (_i > 0) {\n sum += (_i % 10);\n _i /= 10;\n }\n return sum;\n}\n\nvoid tests() {\n assert(fraction(4, 3).n == add_int_to_frac(1, fraction(1, 3)).n);\n assert(fraction(4, 3).d == add_int_to_frac(1, fraction(1, 3)).d);\n\n assert(fraction(11, 4).n == add_int_to_frac(2, fraction(3, 4)).n);\n assert(fraction(11, 4).d == add_int_to_frac(2, fraction(3, 4)).d);\n\n assert(fraction(3, 4).n == int_over_frac(1, fraction(4, 3)).n);\n assert(fraction(3, 4).d == int_over_frac(1, fraction(4, 3)).d);\n\n assert(17 == sum_digits(1457));\n}\n\nint main() {\n // Generate first n numbers of the e convergence sequence.\n size_t n = 100;\n std::vector e_seq = e_sequence(n);\n\n // Compute the convergence of e until n.\n fraction curr(1, e_seq[e_seq.size() - 1]);\n int i = e_seq.size() - 2;\n while (i >= 0) {\n if (i == 0) {\n curr = add_int_to_frac(e_seq[i], curr);\n } else {\n curr = int_over_frac(1, add_int_to_frac(e_seq[i], curr));\n }\n i--;\n }\n\n std::cout << \"Result: \" << curr.n << \"/\" << curr.d << std::endl;\n std::cout << \"Sum of the digits in the numerator: \" << sum_digits(curr.n)\n << std::endl;\n return 0;\n}", "meta": {"hexsha": "212f3b8ce4580c3ead48870bac522baac98a4778", "size": 2155, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/problems/p065.cpp", "max_stars_repo_name": "harrytodorov/ProjectEuler", "max_stars_repo_head_hexsha": "4d0d207320c7b90bd3ad79233669661590723f33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/src/problems/p065.cpp", "max_issues_repo_name": "harrytodorov/ProjectEuler", "max_issues_repo_head_hexsha": "4d0d207320c7b90bd3ad79233669661590723f33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/src/problems/p065.cpp", "max_forks_repo_name": "harrytodorov/ProjectEuler", "max_forks_repo_head_hexsha": "4d0d207320c7b90bd3ad79233669661590723f33", "max_forks_repo_licenses": ["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.7701149425, "max_line_length": 75, "alphanum_fraction": 0.592575406, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813538993888, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7987066888348492}} {"text": "#include \n#include \n#include \"gnuplot-iostream.h\"\n#include \n#include \"sysfunc_exercise2_2_a.h\"\n\nusing Eigen::Matrix3cd;\nusing Eigen::Matrix3d;\nnamespace odeint = boost::numeric::odeint;\n\nint main(int argc, char const *argv[])\n{\n Matrix3d A;\n A << 0, 1, 0,\n 0, 0, 1,\n 2, 1, -2;\n std::cout << \"Here is the matrix A:\\n\"\n << A << std::endl;\n\n Eigen::EigenSolver eigenSolver(A);\n if (eigenSolver.info() != Eigen::Success)\n abort();\n std::cout << \"The eigenvalues of A are:\\n\"\n << eigenSolver.eigenvalues() << std::endl;\n std::cout << \"Here's a matrix whose columns are eigenvectors of A \\n\"\n << \"corresponding to these eigenvalues:\\n\"\n << eigenSolver.eigenvectors() << std::endl;\n\n Matrix3cd T = eigenSolver.eigenvectors();\n Matrix3cd T_inverse = T.inverse();\n Matrix3cd D = T_inverse * A * T;\n\n std::cout << \"The diagonlized Matrix D is:\\n\"\n << D << std::endl;\n\n // Odient Code ...\n std::vector x_vec;\n std::vector times;\n std::vector position;\n {\n system_function::state_type x(3); // a vector with size 3. [x; x_dot; x_dot_dot]\n //x = {1, 1, 1}; // start at x=1, 1, 1;\n x = {1, -1, 1};\n size_t steps = odeint::integrate(system_function::harmonic_oscillator,\n x, 0.0, 10.0, 0.1,\n system_function::push_back_state_and_time(x_vec, times)); //time should be there?\n\n for (size_t i = 0; i <= steps; i++)\n {\n position.push_back(x_vec[i][0]);\n }\n }\n\n // GNU Plot\n {\n /* output */\n Gnuplot gp;\n gp << \"plot '-' using 1:2 with linespoint\" << std::endl;\n gp.send1d(std::make_tuple(times, position));\n }\n\n return 0;\n}\n", "meta": {"hexsha": "1a4cbf5ce020820171ad00b4a2c60fd6506dd671", "size": 1952, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HW/hw2/src/exercise2_2_a.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": "HW/hw2/src/exercise2_2_a.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": "HW/hw2/src/exercise2_2_a.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": 30.5, "max_line_length": 122, "alphanum_fraction": 0.5461065574, "num_tokens": 559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.798492365315217}} {"text": "#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace arma;\n\nvec SteepestDescent(mat A, vec b, vec x0, int dim){\n int IterMax, i;\n const double tolerance = 1.0e-14;\n vec x(dim),r(dim),t(dim);\n double c ,alpha,d;\n IterMax = 20;\n x = x0;\n r = A*x-b;\n i = 0;\n while (i <= IterMax || sqrt(dot(r,r)) < tolerance ){\n if(sqrt(dot(r,r))\n#include \n#include \n\ntypedef boost::multiprecision::number, boost::multiprecision::expression_template_option::et_off> cpp_bin_float_half;\n\n/*\nFrom Wikipedia, the free encyclopedia\nhttps://en.wikipedia.org/wiki/Conjugate_gradient_method\n\nIn mathematics, the conjugate gradient method is an algorithm for the numerical solution of particular \nsystems of linear equations, namely those whose matrix is symmetric and positive-definite. \nThe conjugate gradient method is often implemented as an iterative algorithm, applicable to \nsparse systems that are too large to be handled by a direct implementation or other direct methods \nsuch as the Cholesky decomposition. Large sparse systems often arise when numerically solving \npartial differential equations or optimization problems.\n\nThe conjugate gradient method can also be used to solve unconstrained optimization problems \nsuch as energy minimization. It was mainly developed by Magnus Hestenes and Eduard Stiefel who programmed it on the Z4.\n\nThe biconjugate gradient method provides a generalization to non-symmetric matrices. \nVarious nonlinear conjugate gradient methods seek minima of nonlinear equations.\n */\n\n// Conjugate Gradient algorithm, returns the iteration number of convergence\ntemplate\nunsigned CG(const Matrix& A, const Vector& b, Vector& x, Real epsilon) {\n\tusing namespace sw::hprblas;\n\t//using Real = Vector::value_type;\n\t// starting x is provided by calling context\n\tunsigned k = 0;\n\tVector r = b;\n\tReal error = mtl::two_norm(r);\n\tVector p = r;\n\tVector Ap(size(p)); // need to create the vector to be the same structure as p as the expression (A * p) doesn't do it\n\twhile (error > epsilon) {\n\t\tAp = A * p;\n\t\tReal alpha = dot(r, r) / dot(p, Ap);\n\t\tx = x + alpha * p;\n\t\tVector r_prev = r;\n\t\tr = r - alpha * A * p;\n\t\terror = mtl::two_norm(r);\n\t\tReal beta = dot(r, r) / dot(r_prev, r_prev);\n\t\tp = r + beta * p;\n\t\tstd::cout << \"iteration: \" << std::setw(4) << k\n\t\t\t<< \" alpha: \" << std::setw(12) << alpha\n\t\t\t<< \" beta: \" << std::setw(12) << beta\n\t\t\t<< \" error : \" << error << std::endl;\n\t\t++k;\n\t\tif (k > 1.5* size(b)) break;\n\t}\n\treturn k;\n}\n\n// Conjugate Gradient algorithm, returns the iteration number of convergence\ntemplate\nunsigned fdpCG(const Matrix& A, const Vector& b, Vector& x, Real epsilon) {\n\tusing namespace sw::universal;\n\t//using Real = Vector::value_type;\n\t// starting x is provided by calling context\n\tunsigned k = 0;\n\tVector r = b;\n\tReal error = mtl::two_norm(r);\n\tVector p = r;\n\tVector Ap(size(p)); // need to create the vector to be the same structure as p as the expression (A * p) doesn't do it\n\twhile (error > epsilon) {\n\t\tAp = A * p;\n\t\tReal alpha = fdp(r, r) / fdp(p, Ap);\n\t\tx = x + alpha * p;\n\t\tVector r_prev = r;\n\t\tr = r - alpha * A * p;\n\t\tReal beta = fdp(r, r) / fdp(r_prev, r_prev);\n\t\tp = r + beta * p;\n\t\terror = mtl::two_norm(r);\n\t\tstd::cout << \"iteration: \" << std::setw(4) << k \n\t\t\t<< \" alpha: \" << std::setw(12) << alpha \n\t\t\t<< \" beta: \" << std::setw(12) << beta \n\t\t\t<< \" error : \" << error << std::endl;\n\n\t\t++k;\n\t\tif (k > 1.5* size(b)) break;\n\t}\n\treturn k;\n}\n\n// Conjugate Gradient algorithm, returns the iteration number of convergence\ntemplate\nunsigned fdp2CG(const Matrix& A, const Vector& b, Vector& x, Real epsilon) {\n\tusing namespace sw::universal;\n\t//using Real = Vector::value_type;\n\t// starting x is provided by calling context\n\tunsigned k = 0;\n\tVector r = b;\n\tReal error = mtl::two_norm(r);\n\tVector p = r;\n\tVector Ap(size(p)); // need to create the vector to be the same structure as p as the expression (A * p) doesn't do it\n\twhile (error > epsilon) {\n\t\tsw::hprblas::matvec(Ap, A, p); // Ap = A * p\n\t\tReal alpha = fdp(r, r) / fdp(p, Ap);\n\t\tx = x + alpha * p;\n\t\tVector r_prev = r;\n\t\tr = r - alpha * Ap;\n\t\tReal beta = fdp(r, r) / fdp(r_prev, r_prev);\n\t\tp = r + beta * p;\n\t\terror = mtl::two_norm(r);\n\t\tstd::cout << \"iteration: \" << std::setw(4) << k\n\t\t\t<< \" alpha: \" << std::setw(12) << alpha\n\t\t\t<< \" beta: \" << std::setw(12) << beta\n\t\t\t<< \" error : \" << error << std::endl;\n\n\t\t++k;\n\t\tif (k > 1.5* size(b)) break;\n\t}\n\treturn k;\n}\n\ntemplate\nvoid CGdriver(unsigned N, Real epsilon) {\n\tusing namespace std;\n\tusing namespace mtl;\n\tusing Matrix = mtl::dense2D;\n\tusing Vector = mtl::dense_vector;\n\n\tMatrix A(N, N);\n\tmat::laplacian_setup(A, N, 1);\n\t//cout << A << endl;\n\n\tVector b(N), x(N), ones(N);\n\tones = Real(1);\n\tb = A * ones;\n\tx = Real(0.0); // starting x\n\tcout << b << endl;\n\tunsigned k = CG(A, b, x, epsilon);\n\tcout << \"solution: \" << x << \" at iteration: \" << k << endl;\n\n\tVector error(N);\n\terror = ones - x;\n\tcout << \"exact error is: \" << two_norm(error) << endl;\n}\n\n// CG with fdp applied to alpha/beta calculation only\ntemplate\nvoid fdpCGdriver(unsigned N, sw::universal::posit epsilon) {\n\tusing namespace std;\n\tusing namespace mtl;\n\tusing Real = sw::universal::posit;\n\tusing Matrix = mtl::dense2D;\n\tusing Vector = mtl::dense_vector;\n\n\tMatrix A(N, N);\n\tmat::laplacian_setup(A, N, 1);\n\t//cout << A << endl;\n\n\tVector b(N), x(N), ones(N);\n\tones = Real(1);\n\tb = A * ones;\n\tx = Real(0.0); // starting x\n\tcout << b << endl;\n\tunsigned k = fdpCG(A, b, x, epsilon);\n\tcout << \"solution: \" << x << \" at iteration: \" << k << endl;\n\n\tVector error(N);\n\terror = ones - x;\n\tcout << \"exact error is: \" << two_norm(error) << endl;\n}\n\n// CG with fdp applied to alpha/beta and to matvec A * p as well\ntemplate\nvoid fdp2CGdriver(unsigned N, sw::universal::posit epsilon) {\n\tusing namespace std;\n\tusing namespace mtl;\n\tusing Real = sw::universal::posit;\n\tusing Matrix = mtl::dense2D;\n\tusing Vector = mtl::dense_vector;\n\n\tMatrix A(N, N);\n\tmat::laplacian_setup(A, N, 1);\n\t//cout << A << endl;\n\n\tVector b(N), x(N), ones(N);\n\tones = Real(1);\n\tb = A * ones;\n\tx = Real(0.0); // starting x\n\tcout << b << endl;\n\tunsigned k = fdp2CG(A, b, x, epsilon);\n\tcout << \"solution: \" << x << \" at iteration: \" << k << endl;\n\n\tVector error(N);\n\terror = ones - x;\n\tcout << \"exact error is: \" << two_norm(error) << endl;\n}\n\n// CG test program\nint main(int argc, char** argv)\ntry {\n\tusing namespace std;\n\tusing namespace sw::universal;\n\n\tstring separation_string = \"=================================================================\\n\";\n\tconstexpr unsigned N = 10;\n\tlong double accuracy = 1.0e-3;\n\n\t{\n\t\tconstexpr size_t nbits = 16;\n\t\tconstexpr size_t es = 1;\n\t\tusing Real = posit;\n\t\tReal pminpos; minpos(pminpos);\n\t\tcout << \"type: \" << typeid(Real).name() << endl;\n\t\tcout << \"minpos : \" << pminpos << endl;\n\t\tReal epsilon = Real(accuracy);\n\t\tCGdriver(N, epsilon);\n\t}\n\t\n\tcout << separation_string;\n\t{\n\t\tusing Real = cpp_bin_float_half;\n\t\tcout << \"type: \" << typeid(Real).name() << endl;\n\t\tReal epsilon = Real(accuracy);\n\t\tCGdriver(N, epsilon);\n\t}\n\tcout << separation_string;\n\t{\n\t\tconstexpr size_t nbits = 16;\n\t\tconstexpr size_t es = 1;\n\t\tusing Real = posit;\n\t\tReal pminpos; minpos(pminpos);\n\t\tcout << \"type: \" << typeid(Real).name() << endl;\n\t\tcout << \"minpos : \" << pminpos << endl;\n\t\tReal epsilon = Real(accuracy);\n\t\tCGdriver(N, epsilon);\n\t\tfdpCGdriver(N, epsilon);\n\t\tfdp2CGdriver(N, epsilon);\n\t}\n\n\treturn EXIT_SUCCESS;\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": "24afeba5c8ea018f915e2306053b09deedeec22a", "size": 8556, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/numerical/conjugate_gradient.cpp", "max_stars_repo_name": "shikharvashistha/hpr-blas", "max_stars_repo_head_hexsha": "73f109d45701fc3816af0a1ecd42f11d494a6f97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-07T11:30:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-07T11:30:17.000Z", "max_issues_repo_path": "applications/numerical/conjugate_gradient.cpp", "max_issues_repo_name": "jamesquinlan/hpr-blas", "max_issues_repo_head_hexsha": "2975b4378b36a0bdc55d0dbd4f979163f7009678", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/numerical/conjugate_gradient.cpp", "max_forks_repo_name": "jamesquinlan/hpr-blas", "max_forks_repo_head_hexsha": "2975b4378b36a0bdc55d0dbd4f979163f7009678", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1654135338, "max_line_length": 246, "alphanum_fraction": 0.6577840112, "num_tokens": 2448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545274901876, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7981807950363372}} {"text": "#pragma once\n\n#include \n#include \n\nusing namespace Eigen;\n\n\n/**\n * @brief Calcola la direzione normale di ogni vertice nella mesh in input.\n *\n * Data una mesh di triangoli M = (V, F), dove V e' un array di posizioni 3D\n * (i vertici) e F e' un array di triple di indici ai vertici (ogni tripla\n * rappresenta una faccia triangolare), questa funzione calcola la direzione\n * normale di ogni vertice come una somma pesata delle normali dei triangoli\n * intorno (incidenti) a tale vertice.\n * Il peso è dato dall'area del triangolo moltiplicato l'angolo incidente\n * sul vertice.\n *\n * L'area di un triangolo viene calcolata come meta' della lunghezza (norma)\n * del prodotto vettoriale tra due lati.\n * L'angolo incidente su un vertice viene calcolato come l'arcocoseno del\n * prodotto scalare tra i due lati incidenti (intesi come vettori unitari\n * centrati su di esso), oppure come l'arcotangente del seno e coseno:\n * - il seno e' proporzionale alla normal del prodotto vettoriale\n * - il cose e' proporzionale al prodotto scalare.\n *\n * @param V I vertici della mesh. Per ogni riga della matrice V, la posizione\n * del vertice e' costituita dalle coordinate x,y,z memorizzate nelle\n * 3 colonne della riga.\n * @param F I triangoli della mesh. Per ogni riga della matrice F, il triangolo\n * e' descritto dagli indici i,j,k memorizzati nelle 3 colonne della\n * riga. Gli indici i,j,k si riferiscono ai 3 vertici A, B, C del\n * triangolo, memorizzati in V.row(i), V.row(j) e V.row(k),\n * rispettivamente. NOTA: per ogni triangolo, i 3 vertici sono da\n * considerarsi indicati in senso antiorario.\n * @return MatrixXd La matrice restituita ha una riga per ogni vertice\n * (N.rows() == V.rows()) e 3 colonne. Ogni riga corrisponde\n * alla direzione normale del vertice corrispondente, avente\n * le 3 coordinate x,y,z.\n */\nMatrixXd perVertexNormals(MatrixXd const &V, MatrixXi const &F)\n{\n MatrixXd N = MatrixXd::Zero(V.rows(), 3);\n\n // per leggere/scrivere un elemento di una matrice X: X(i,j)\n // per leggere/scrivere una riga di una matrice X: X.row(i) (un vettore orizzontale)\n // il vettore da un punto p0 a un altro punto p1: Vector3d v = p1 - p0;\n // il prodotto vettoriale tra 2 vettori: Vector3d c = v1.cross(v2);\n // normalizzare un vettore, in-place: c.normalize();\n // normalizzare un vettore, in una nuova variabile: Vector3d cn = c.normalized();\n // lunghezza (norma) di un vettore: v.norm();\n // angolo tra due vettori normalizzati: std::acos(n1.dot(n2));\n // angolo tra due vettori non-normalizzati: std::atan2(v1.cross(v2).norm(), v1.dot(v2));\n\n for (int f = 0; f < F.rows(); ++f)\n {\n int i = F(f, 0);\n int j = F(f, 1);\n int k = F(f, 2);\n\n Vector3d A = V.row(i);\n Vector3d B = V.row(j);\n Vector3d C = V.row(k);\n\n Vector3d e0 = B - A;\n Vector3d e1 = C - B;\n Vector3d e2 = A - C;\n\n Vector3d c0 = e0.cross(-e2);\n Vector3d c1 = e1.cross(-e0);\n Vector3d c2 = e2.cross(-e1);\n\n double area = c0.norm() / 2.0;\n\n Vector3d n = c0.normalized();\n\n double a_i = std::atan2(c0.norm(), e0.dot(-e2));\n double a_j = std::atan2(c1.norm(), e1.dot(-e0));\n double a_k = std::atan2(c2.norm(), e2.dot(-e1));\n\n N.row(i) += area * a_i * n;\n N.row(j) += area * a_j * n;\n N.row(k) += area * a_k * n;\n }\n\n for (int v = 0; v < V.rows(); ++v) {\n N.row(v).normalize();\n }\n\n return N;\n}", "meta": {"hexsha": "e4a214020a7a236e1bc17372b452692cc61f5f95", "size": 3603, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "perVertexNormals.hpp", "max_stars_repo_name": "giorgiomarcias/WS_geo_3D", "max_stars_repo_head_hexsha": "ea34450ed0daa38504df5c0d723ab41ac347abd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-11T16:16:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-11T16:16:28.000Z", "max_issues_repo_path": "perVertexNormals.hpp", "max_issues_repo_name": "giorgiomarcias/WS_geo_3D", "max_issues_repo_head_hexsha": "ea34450ed0daa38504df5c0d723ab41ac347abd3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "perVertexNormals.hpp", "max_forks_repo_name": "giorgiomarcias/WS_geo_3D", "max_forks_repo_head_hexsha": "ea34450ed0daa38504df5c0d723ab41ac347abd3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1630434783, "max_line_length": 92, "alphanum_fraction": 0.6280877047, "num_tokens": 1137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545289551958, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7981807943883212}} {"text": "// Implements functions that fit conics to data using linear least squares methods.\n// File: conicfit.cpp\n// Author: Philipp Allgeuer \n\n// Includes\n#include \n#include \n#include \n#include \n#include \n#include \n\n// Namespaces\nusing namespace rc_utils;\n\n// Fitting problems can often be expressed as an overconstrained set of linear equations Ax = b. Such a set of equations is generally\n// solved by treating it as a least squares problem. The task is then to find a vector xhat that has the smallest residual squared\n// error in satisfying Ax = b. It is a well-known result that the required minimising solution is given by:\n// xhat = (A'A)\\(A'b) {Matlab style}\n// Or equivalently:\n// xhat = (A^T * A)^-1 * A^T * b {Explicit style}\n// The exact residual sum being minimised is:\n// J(x) = norm(b - Ax)^2\n\n// Constants\nconst double ConicFit::ZeroTol = 1e-12;\n\n//\n// Circle fitting\n//\n\n// Fit a circle to 2D data\nvoid ConicFit::fitCircle(const Points2D& P, Eigen::Vector2d& centre, double& radius)\n{\n\t// Suppose the i-th data point is (xi,yi). We try to fit a circle of radius R and centre (cx,cy) to the data. Let:\n\t// A = N rows of [xi yi 1] {Nx3 matrix}\n\t// x = [2*cx; 2*cy; R^2-cx^2-cy^2] {3x1 column vector}\n\t// b = N rows of [xi^2 + yi^2] {Nx1 column vector}\n\t// Ax = b is equivalent to the condition that all data points lie on a circle of radius R, centered at (cx,cy).\n\t// Hence by solving Ax = b for x in a least squares sense, we are implicitly solving for the values of cx, cy, R\n\t// for which the corresponding circle most closely fits the data. We perform a mean shift on the data for\n\t// numerical conditioning and stability reasons.\n\t\n\t// Declare variables\n\tsize_t N = P.size();\n\tEigen::MatrixXd A(N, 3);\n\tEigen::VectorXd b(N);\n\t\n\t// Calculate the mean of the data points\n\tEigen::Vector2d mean = Eigen::Vector2d::Zero();\n\tif(N >= 1)\n\t\tmean = std::accumulate(P.begin(), P.end(), mean) / N;\n\t\n\t// Construct the linear equation to solve (Ax = b)\n\tfor(size_t i = 0; i < N; i++)\n\t{\n\t\tconst Eigen::Vector2d p = P[i] - mean;\n\t\tA(i, 0) = p.x();\n\t\tA(i, 1) = p.y();\n\t\tA(i, 2) = 1.0;\n\t\tb(i) = p.squaredNorm();\n\t}\n\t\n\t// Call the worker function to fit the circle\n\tfitCircle(A, b, centre, radius);\n\t\n\t// Correct for the applied mean shift\n\tcentre += mean;\n}\n\n// Fit a circle to the XY components of 3D data\nvoid ConicFit::fitCircle(const Points3D& P, Eigen::Vector3d& centre, double& radius)\n{\n\t// We discard the z coordinates and fit a circle as normal for 2D data.\n\t// The returned centre z coordinate is a plain mean of the input z coordinates.\n\t\n\t// Declare variables\n\tsize_t N = P.size();\n\tEigen::MatrixXd A(N, 3);\n\tEigen::VectorXd b(N);\n\t\n\t// Calculate the mean of the data points\n\tEigen::Vector3d mean = Eigen::Vector3d::Zero();\n\tif(N >= 1)\n\t\tmean = std::accumulate(P.begin(), P.end(), mean) / N;\n\t\n\t// Construct the linear equation to solve (Ax = b)\n\tfor(size_t i = 0; i < N; i++)\n\t{\n\t\tconst Eigen::Vector3d p = P[i] - mean;\n\t\tA(i, 0) = p.x();\n\t\tA(i, 1) = p.y();\n\t\tA(i, 2) = 1.0;\n\t\tb(i) = p.x()*p.x() + p.y()*p.y();\n\t}\n\t\n\t// Call the worker function to fit the circle\n\tEigen::Vector2d centre2D;\n\tfitCircle(A, b, centre2D, radius);\n\t\n\t// Correct for the applied mean shift\n\tcentre.x() = mean.x() + centre2D.x();\n\tcentre.y() = mean.y() + centre2D.y();\n\tcentre.z() = mean.z();\n}\n\n// Worker function for fitting a circle\nvoid ConicFit::fitCircle(const Eigen::MatrixXd& A, const Eigen::VectorXd& b, Eigen::Vector2d& centre, double& radius)\n{\n\t// Find the least squares solution to Ax = b using Singular Value Decomposition (linear least squares fitting)\n\tEigen::VectorXd coefficients = A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);\n\t\n\t// Extract the centre and radius of the fitted circle\n\tcentre.x() = 0.5*coefficients(0);\n\tcentre.y() = 0.5*coefficients(1);\n\tradius = sqrt(coefficients(2) + centre.squaredNorm());\n}\n\n// Fit a circle of known centre to 2D data\nvoid ConicFit::fitCircleCentred(const Points2D& P, const Eigen::Vector2d& centre, double& radius)\n{\n\t// Suppose the i-th data point is (xi,yi). The least squares solution to finding a circle of radius R of known centre\n\t// (cx,cy) that best fits the data points has a simple algebraic solution, given by:\n\t// R = sqrt(sum((xi-cx)^2 + (yi-cy)^2, 1, N) / N)\n\t// In other words, the radius of best fit is the quadratic mean of the distances from the known centre to each point.\n\t\n\t// Declare variables\n\tsize_t N = P.size();\n\t\n\t// Calculate the radius of best fit\n\tdouble Rsq = 0.0;\n\tfor(size_t i = 0; i < N; i++)\n\t\tRsq += (P[i] - centre).squaredNorm() / N;\n\tradius = sqrt(Rsq);\n}\n\n// Fit a circle of known centre to the XY components of 3D data\nvoid ConicFit::fitCircleCentred(const Points3D& P, const Eigen::Vector3d& centre, double& radius)\n{\n\t// We discard the z coordinates and fit a circle of known centre as normal for 2D data.\n\t\n\t// Declare variables\n\tsize_t N = P.size();\n\tEigen::Vector2d centre2D = centre.head<2>();\n\t\n\t// Calculate the radius of best fit\n\tdouble Rsq = 0.0;\n\tfor(size_t i = 0; i < N; i++)\n\t\tRsq += (P[i].head<2>() - centre2D).squaredNorm() / N;\n\tradius = sqrt(Rsq);\n}\n\n// Calculate the fitting error of a circle to certain 2D data\ndouble ConicFit::fitCircleError(const Points2D& P, const Eigen::Vector2d& centre, double radius)\n{\n\t// The returned error is the average distance to the circle in units of circle radii.\n\t\n\t// Calculate and return the required dimensionless fitting error\n\tsize_t N = P.size();\n\tif(N <= 0) return 0.0;\n\tdouble err = 0.0;\n\tif(radius != 0.0)\n\t{\n\t\tfor(size_t i = 0; i < N; i++)\n\t\t\terr += fabs((P[i] - centre).norm() - radius);\n\t\terr /= N*fabs(radius);\n\t}\n\telse\n\t{\n\t\tfor(size_t i = 0; i < N; i++)\n\t\t\terr += fabs((P[i] - centre).norm());\n\t\terr /= N;\n\t}\n\treturn err;\n}\n\n// Calculate the fitting error of a circle to certain 3D data\ndouble ConicFit::fitCircleError(const Points3D& P, const Eigen::Vector3d& centre, double radius)\n{\n\t// The returned error is the average planar XY distance to the circle in units of circle radii.\n\t\n\t// Calculate and return the required dimensionless fitting error\n\tsize_t N = P.size();\n\tif(N <= 0) return 0.0;\n\tEigen::Vector2d centre2D = centre.head<2>();\n\tdouble err = 0.0;\n\tif(radius != 0.0)\n\t{\n\t\tfor(size_t i = 0; i < N; i++)\n\t\t\terr += fabs((P[i].head<2>() - centre2D).norm() - radius);\n\t\terr /= N*fabs(radius);\n\t}\n\telse\n\t{\n\t\tfor(size_t i = 0; i < N; i++)\n\t\t\terr += fabs((P[i].head<2>() - centre2D).norm());\n\t\terr /= N;\n\t}\n\treturn err;\n}\n\n//\n// Weighted circle fitting\n//\n\n// Fit a weighted circle to 2D data\nvoid ConicFit::fitCircleWeighted(const WeightedPoints2D& P, Eigen::Vector2d& centre, double& radius)\n{\n\t// Suppose the i-th data point is (xi,yi,wi). We try to fit a circle of radius R and centre (cx,cy) to the data. Let:\n\t// A = N rows of [wi*xi wi*yi wi] {Nx3 matrix}\n\t// x = [2*cx; 2*cy; R^2-cx^2-cy^2] {3x1 column vector}\n\t// b = N rows of [wi*(xi^2 + yi^2)] {Nx1 column vector}\n\t// Ax = b is equivalent to the weighted condition that all data points lie on a circle of radius R, centered at (cx,cy).\n\t// Hence by solving Ax = b for x in a least squares sense, we are implicitly solving for the values of cx, cy, R\n\t// for which the corresponding circle most closely fits the weighted data. We perform a mean shift on the data for\n\t// numerical conditioning and stability reasons.\n\t\n\t// Declare variables\n\tsize_t N = P.size();\n\tEigen::MatrixXd A(N, 3);\n\tEigen::VectorXd b(N);\n\t\n\t// Calculate the mean of the data points\n\tEigen::Vector2d mean = Eigen::Vector2d::Zero();\n\tfor(size_t i = 0; i < N; i++)\n\t\tmean += P[i].head<2>();\n\tif(N >= 1)\n\t\tmean /= N;\n\t\n\t// Construct the linear equation to solve (Ax = b)\n\tfor(size_t i = 0; i < N; i++)\n\t{\n\t\tconst Eigen::Vector2d p = P[i].head<2>() - mean;\n\t\tdouble w = P[i].z();\n\t\tA(i, 0) = w*p.x();\n\t\tA(i, 1) = w*p.y();\n\t\tA(i, 2) = w;\n\t\tb(i) = w*p.squaredNorm();\n\t}\n\t\n\t// Call the worker function to fit the circle\n\tfitCircle(A, b, centre, radius);\n\t\n\t// Correct for the applied mean shift\n\tcentre += mean.head<2>();\n}\n\n// Fit a weighted circle to 2D data\nvoid ConicFit::fitCircleWeighted(const Points2D& P, const Weights& W, Eigen::Vector2d& centre, double& radius)\n{\n\t// Suppose the i-th data point is (xi,yi,wi). We try to fit a circle of radius R and centre (cx,cy) to the data. Let:\n\t// A = N rows of [wi*xi wi*yi wi] {Nx3 matrix}\n\t// x = [2*cx; 2*cy; R^2-cx^2-cy^2] {3x1 column vector}\n\t// b = N rows of [wi*(xi^2 + yi^2)] {Nx1 column vector}\n\t// Ax = b is equivalent to the weighted condition that all data points lie on a circle of radius R, centered at (cx,cy).\n\t// Hence by solving Ax = b for x in a least squares sense, we are implicitly solving for the values of cx, cy, R\n\t// for which the corresponding circle most closely fits the weighted data. We perform a mean shift on the data for\n\t// numerical conditioning and stability reasons.\n\t\n\t// Error checking\n\tsize_t N = P.size();\n\tif(N != W.size())\n\t{\n\t\tcentre.setZero();\n\t\tradius = 0.0;\n\t\treturn;\n\t}\n\t\n\t// Declare variables\n\tEigen::MatrixXd A(N, 3);\n\tEigen::VectorXd b(N);\n\t\n\t// Calculate the mean of the data points\n\tEigen::Vector2d mean = Eigen::Vector2d::Zero();\n\tif(N >= 1)\n\t\tmean = std::accumulate(P.begin(), P.end(), mean) / N;\n\t\n\t// Construct the linear equation to solve (Ax = b)\n\tfor(size_t i = 0; i < N; i++)\n\t{\n\t\tconst Eigen::Vector2d p = P[i] - mean;\n\t\tdouble w = W[i];\n\t\tA(i, 0) = w*p.x();\n\t\tA(i, 1) = w*p.y();\n\t\tA(i, 2) = w;\n\t\tb(i) = w*p.squaredNorm();\n\t}\n\t\n\t// Call the worker function to fit the circle\n\tfitCircle(A, b, centre, radius);\n\t\n\t// Correct for the applied mean shift\n\tcentre += mean;\n}\n\n// Fit a weighted circle of known centre to 2D data\nvoid ConicFit::fitCircleCentredWeighted(const WeightedPoints2D& P, const Eigen::Vector2d& centre, double& radius)\n{\n\t// Suppose the i-th data point is (xi,yi,wi). The least squares solution to finding a circle of radius R of known centre\n\t// (cx,cy) that best fits the data points has a simple algebraic solution, given by:\n\t// R = sqrt(sum(wi^2*((xi-cx)^2 + (yi-cy)^2), 1, N) / sum(wi^2, 1, N))\n\t// In other words, the radius of best fit is the weighted quadratic mean of the distances from the known centre to each point,\n\t// using weights the squares of those that are passed (to be consistent with the definition of the weights in other fitCircle functions).\n\t\n\t// Declare variables\n\tsize_t N = P.size();\n\t\n\t// Calculate the radius of best fit\n\tdouble Rsq = 0.0, wsqsum = 0.0;\n\tfor(size_t i = 0; i < N; i++)\n\t{\n\t\tdouble w = P[i].z();\n\t\tdouble wsq = w*w;\n\t\tRsq += wsq*((P[i].head<2>() - centre).squaredNorm());\n\t\twsqsum += wsq;\n\t}\n\tif(wsqsum > 0.0)\n\t\tradius = sqrt(Rsq / wsqsum);\n\telse\n\t\tradius = 0.0;\n}\n\n// Fit a weighted circle of known centre to 2D data\nvoid ConicFit::fitCircleCentredWeighted(const Points2D& P, const Weights& W, const Eigen::Vector2d& centre, double& radius)\n{\n\t// Suppose the i-th data point is (xi,yi,wi). The least squares solution to finding a circle of radius R of known centre\n\t// (cx,cy) that best fits the data points has a simple algebraic solution, given by:\n\t// R = sqrt(sum(wi^2*((xi-cx)^2 + (yi-cy)^2), 1, N) / sum(wi^2, 1, N))\n\t// In other words, the radius of best fit is the weighted quadratic mean of the distances from the known centre to each point,\n\t// using weights the squares of those that are passed (to be consistent with the definition of the weights in other fitCircle functions).\n\t\n\t// Error checking\n\tsize_t N = P.size();\n\tif(N != W.size())\n\t{\n\t\tradius = 0.0;\n\t\treturn;\n\t}\n\t\n\t// Calculate the radius of best fit\n\tdouble Rsq = 0.0, wsqsum = 0.0;\n\tfor(size_t i = 0; i < N; i++)\n\t{\n\t\tdouble w = W[i];\n\t\tdouble wsq = w*w;\n\t\tRsq += wsq*((P[i] - centre).squaredNorm());\n\t\twsqsum += wsq;\n\t}\n\tif(wsqsum > 0.0)\n\t\tradius = sqrt(Rsq / wsqsum);\n\telse\n\t\tradius = 0.0;\n}\n\n// Calculate the weighted fitting error of a circle to certain 2D data (the returned error is the weighted average distance of the data points to the circle in units of circle radii)\ndouble ConicFit::fitCircleErrorWeighted(const WeightedPoints2D& P, const Eigen::Vector2d& centre, double radius)\n{\n\t// Calculate and return the required dimensionless fitting error\n\tsize_t N = P.size();\n\tif(N <= 0) return 0.0;\n\tradius = fabs(radius);\n\tdouble err = 0.0, wsum = 0.0;\n\tfor(size_t i = 0; i < N; i++)\n\t{\n\t\tdouble w = fabs(P[i].z());\n\t\terr += w*fabs((P[i].head<2>() - centre).norm() - radius);\n\t\twsum += w;\n\t}\n\tif(wsum == 0.0)\n\t\terr = 0.0;\n\telse\n\t{\n\t\tif(radius != 0.0)\n\t\t\terr /= radius;\n\t\terr /= wsum;\n\t}\n\treturn err;\n}\n\n// Calculate the weighted fitting error of a circle to certain 2D data (the returned error is the weighted average distance of the data points to the circle in units of circle radii)\ndouble ConicFit::fitCircleErrorWeighted(const Points2D& P, const Weights& W, const Eigen::Vector2d& centre, double radius)\n{\n\t// Calculate and return the required dimensionless fitting error\n\tsize_t N = P.size();\n\tif(N != W.size()) return 1e16;\n\tif(N <= 0) return 0.0;\n\tradius = fabs(radius);\n\tdouble err = 0.0, wsum = 0.0;\n\tfor(size_t i = 0; i < N; i++)\n\t{\n\t\tdouble w = fabs(W[i]);\n\t\terr += w*fabs((P[i] - centre).norm() - radius);\n\t\twsum += w;\n\t}\n\tif(wsum == 0.0)\n\t\terr = 0.0;\n\telse\n\t{\n\t\tif(radius != 0.0)\n\t\t\terr /= radius;\n\t\terr /= wsum;\n\t}\n\treturn err;\n}\n\n\n//\n// Ellipse fitting\n//\n\n// Fit an ellipse to 2D data\nvoid ConicFit::fitEllipse(const Points2D& P, Eigen::Vector2d& centre, Eigen::Matrix2d& coeff)\n{\n\t// We first compute the mean point (xm,ym) of the data points, and bias the data points by the negative of this, resulting in zero mean data.\n\t// Suppose that the zero mean set of points is (xi,yi). We then fit the following equation by least squares:\n\t// ax^2 + by^2 + 2cxy + 2dx + 2ey = 1\n\t// We do this by expressing the least squares fitting problem as the matrix equation Dv = y, where:\n\t// D = N rows of [xi^2 yi^2 2*xi*yi 2*xi 2*yi] {Nx5 matrix}\n\t// v = [a; b; c; d; e] {5x1 column vector}\n\t// y = N rows of [1] {Nx1 column vector}\n\t// The centre of the ellipse is at the point where the gradient of ax^2 + by^2 + 2cxy + 2dx + 2ey is zero. Therefore, accounting for (xm,ym):\n\t// [cx; cy] = [xm; ym] - [a c; c b] \\ [d; e] {Matlab style}\n\t// (cx,cy) is the centre of the ellipse of best fit through the original data points. The coefficient matrix is then computed by fitting an\n\t// ellipse of known centre (cx,cy) through the data points. If A is the resulting coefficient matrix, the ellipse of best fit is:\n\t// (x-c)'A(x-c) = 1\n\t// where x = [x; y] and c = [cx; cy] are column vectors.\n\t\n\t// Declare variables\n\tsize_t N = P.size();\n\tEigen::MatrixXd D(N, 5);\n\tEigen::VectorXd y(N);\n\t\n\t// Calculate the mean of the data points\n\tEigen::Vector2d mean = Eigen::Vector2d::Zero();\n\tif(N >= 1)\n\t\tmean = std::accumulate(P.begin(), P.end(), mean) / N;\n\t\n\t// Construct the linear equation to solve (Dv = y)\n\tfor(size_t i = 0; i < N; i++)\n\t{\n\t\tconst Eigen::Vector2d p = P[i] - mean;\n\t\tD(i, 0) = p.x()*p.x();\n\t\tD(i, 1) = p.y()*p.y();\n\t\tD(i, 2) = 2.0*p.x()*p.y();\n\t\tD(i, 3) = 2.0*p.x();\n\t\tD(i, 4) = 2.0*p.y();\n\t\ty(i) = 1.0;\n\t}\n\t\n\t// Compute the centre of the ellipse of best fit\n\tfitEllipse(mean, D, y, centre);\n\t\n\t// Compute the coefficient matrix of the ellipse of best fit through the nominated centre\n\tfitEllipseCentred(P, centre, coeff);\n}\n\n// Fit an ellipse to the XY components of 3D data\nvoid ConicFit::fitEllipse(const Points3D& P, Eigen::Vector3d& centre, Eigen::Matrix2d& coeff)\n{\n\t// We discard the z coordinates and fit an ellipse as normal for 2D data.\n\t// The returned centre z coordinate is a plain mean of the input z coordinates.\n\t\n\t// Declare variables\n\tsize_t N = P.size();\n\tEigen::MatrixXd D(N, 5);\n\tEigen::VectorXd y(N);\n\t\n\t// Calculate the mean of the data points\n\tEigen::Vector3d mean = Eigen::Vector3d::Zero();\n\tif(N >= 1)\n\t\tmean = std::accumulate(P.begin(), P.end(), mean) / N;\n\t\n\t// Construct the linear equation to solve (Dv = y)\n\tfor(size_t i = 0; i < N; i++)\n\t{\n\t\tconst Eigen::Vector3d p = P[i] - mean;\n\t\tD(i, 0) = p.x()*p.x();\n\t\tD(i, 1) = p.y()*p.y();\n\t\tD(i, 2) = 2.0*p.x()*p.y();\n\t\tD(i, 3) = 2.0*p.x();\n\t\tD(i, 4) = 2.0*p.y();\n\t\ty(i) = 1.0;\n\t}\n\t\n\t// Compute the centre of the ellipse of best fit\n\tEigen::Vector2d centre2D;\n\tfitEllipse(mean.head<2>(), D, y, centre2D);\n\tcentre.x() = centre2D.x();\n\tcentre.y() = centre2D.y();\n\tcentre.z() = mean.z();\n\t\n\t// Compute the coefficient matrix of the ellipse of best fit through the nominated centre\n\tfitEllipseCentred(P, centre, coeff);\n}\n\n// Worker function for fitting an ellipse\nvoid ConicFit::fitEllipse(const Eigen::Vector2d& mean, const Eigen::MatrixXd& D, const Eigen::VectorXd& y, Eigen::Vector2d& centre)\n{\n\t// Find the least squares solution to Dv = y using Singular Value Decomposition (linear least squares fitting)\n\tEigen::VectorXd vhat = D.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(y);\n\t\n\t// Construct the coefficient matrix and vector\n\tEigen::Matrix2d A;\n\tA << vhat(0), vhat(2),\n\t vhat(2), vhat(1);\n\tEigen::Vector2d b(vhat(3), vhat(4));\n\t\n\t// Calculate the centre of the fitted ellipse\n\tcentre = mean - A.colPivHouseholderQr().solve(b);\n}\n\n// Fit an ellipse of known centre to 2D data\nvoid ConicFit::fitEllipseCentred(const Points2D& P, const Eigen::Vector2d& centre, Eigen::Matrix2d& coeff)\n{\n\t// We first bias the data to be relative to the centre (cx,cy) of the ellipse to fit. We then fit the following equation by least squares:\n\t// ax^2 + by^2 + 2cxy = 1\n\t// If we define A = [a c; c b] as the coefficient matrix, and let xc = [x; y] then this is equivalent to:\n\t// xc'*A*xc = 1\n\t// Suppose that the i-th data point of biased data is (xi,yi). We perform the ellipse fit by expressing the least squares fitting problem\n\t// as the matrix equation Dv = y, where:\n\t// D = N rows of [xi^2 yi^2 2*xi*yi] {Nx3 matrix}\n\t// v = [a; b; c] {3x1 column vector}\n\t// y = N rows of [1] {Nx1 column vector}\n\t// The coefficient matrix A can be constructed from the solution v, after which the equation of the ellipse of best fit through the\n\t// original data becomes:\n\t// (x-c)'A(x-c) = 1\n\t// where x = [x; y] and c = [cx; cy] are column vectors, and c is the specified centre of the ellipse.\n\t\n\t// Declare variables\n\tsize_t N = P.size();\n\tEigen::MatrixXd D(N, 3);\n\tEigen::VectorXd y(N);\n\t\n\t// Construct the linear equation to solve (Dv = y)\n\tfor(size_t i = 0; i < N; i++)\n\t{\n\t\tconst Eigen::Vector2d p = P[i] - centre;\n\t\tD(i, 0) = p.x()*p.x();\n\t\tD(i, 1) = p.y()*p.y();\n\t\tD(i, 2) = 2.0*p.x()*p.y();\n\t\ty(i) = 1.0;\n\t}\n\t\n\t// Compute the coefficient matrix of the ellipse of best fit through the nominated centre\n\tfitEllipseCentred(D, y, coeff);\n}\n\n// Fit an ellipse of known centre to the XY components of 3D data\nvoid ConicFit::fitEllipseCentred(const Points3D& P, const Eigen::Vector3d& centre, Eigen::Matrix2d& coeff)\n{\n\t// We discard the z coordinates and fit an ellipse of known centre as normal for 2D data.\n\t\n\t// Declare variables\n\tsize_t N = P.size();\n\tEigen::MatrixXd D(N, 3);\n\tEigen::VectorXd y(N);\n\t\n\t// Construct the linear equation to solve (Dv = y)\n\tfor(size_t i = 0; i < N; i++)\n\t{\n\t\tconst Eigen::Vector3d p = P[i] - centre;\n\t\tD(i, 0) = p.x()*p.x();\n\t\tD(i, 1) = p.y()*p.y();\n\t\tD(i, 2) = 2.0*p.x()*p.y();\n\t\ty(i) = 1.0;\n\t}\n\t\n\t// Compute the coefficient matrix of the ellipse of best fit through the nominated centre\n\tfitEllipseCentred(D, y, coeff);\n}\n\n// Worker function for fitting an ellipse with a known centre\nvoid ConicFit::fitEllipseCentred(const Eigen::MatrixXd& D, const Eigen::VectorXd& y, Eigen::Matrix2d& coeff)\n{\n\t// Find the least squares solution to Dv = y using Singular Value Decomposition (linear least squares fitting)\n\tEigen::VectorXd vhat = D.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(y);\n\t\n\t// Construct the coefficient matrix\n\tcoeff << vhat(0), vhat(2),\n\t vhat(2), vhat(1);\n}\n\n// Calculate the fitting error of an ellipse to certain 2D data (average distance of normalised points to the unit circle)\ndouble ConicFit::fitEllipseErrorCoeff(const Points2D& P, const Eigen::Vector2d& centre, const Eigen::Matrix2d& coeff)\n{\n\t// Declare variables\n\tEigen::Matrix2d rotmat, transform;\n\tEigen::Vector2d radii;\n\tdouble angle;\n\t\n\t// Calculate the transformation matrix\n\tdouble failed = (double) P.size();\n\tif(!ellipseMatrixToAxes(coeff, rotmat, radii, angle)) return failed;\n\tif(!ellipseAxesToTransform(rotmat, radii, transform)) return failed;\n\t\n\t// Calculate the fitting error based on the centre and transformation matrix\n\treturn fitEllipseError(P, centre, transform);\n}\n\n// Calculate the fitting error of an ellipse to certain 2D data (average distance of normalised points to the unit circle)\ndouble ConicFit::fitEllipseError(const Points2D& P, const Eigen::Vector2d& centre, const Eigen::Matrix2d& transform)\n{\n\t// Calculate and return the required dimensionless fitting error\n\tdouble err = 0.0;\n\tsize_t N = P.size();\n\tfor(size_t i = 0; i < N; i++)\n\t\terr += fabs((transform*(P[i] - centre)).norm() - 1.0)/N;\n\treturn err;\n}\n\n// Calculate the fitting error of an ellipse to certain 3D data (average distance of normalised points to the unit circle)\ndouble ConicFit::fitEllipseErrorCoeff(const Points3D& P, const Eigen::Vector3d& centre, const Eigen::Matrix2d& coeff)\n{\n\t// Declare variables\n\tEigen::Matrix2d rotmat, transform;\n\tEigen::Vector2d radii;\n\tdouble angle;\n\t\n\t// Calculate the transformation matrix\n\tdouble failed = (double) P.size();\n\tif(!ellipseMatrixToAxes(coeff, rotmat, radii, angle)) return failed;\n\tif(!ellipseAxesToTransform(rotmat, radii, transform)) return failed;\n\t\n\t// Calculate the fitting error based on the centre and transformation matrix\n\treturn fitEllipseError(P, centre, transform);\n}\n\n// Calculate the fitting error of an ellipse to certain 3D data (average distance of normalised points to the unit circle)\ndouble ConicFit::fitEllipseError(const Points3D& P, const Eigen::Vector3d& centre, const Eigen::Matrix2d& transform)\n{\n\t// Calculate and return the required dimensionless fitting error\n\tdouble err = 0.0;\n\tsize_t N = P.size();\n\tEigen::Vector2d centre2D = centre.head<2>();\n\tfor(size_t i = 0; i < N; i++)\n\t\terr += fabs((transform*(P[i].head<2>() - centre2D)).norm() - 1.0)/N;\n\treturn err;\n}\n\n//\n// Sphere fitting\n//\n\n// Fit a sphere to 3D data\nvoid ConicFit::fitSphere(const Points3D& P, Eigen::Vector3d& centre, double& radius)\n{\n\t// Suppose the i-th data point is (xi,yi,zi). We try to fit a sphere of radius R and centre (cx,cy,cz) to the data. Let:\n\t// A = N rows of [xi yi zi 1] {Nx4 matrix}\n\t// x = [2*cx; 2*cy; 2*cz; R^2-cx^2-cy^2-cz^2] {4x1 column vector}\n\t// b = N rows of [xi^2 + yi^2 + zi^2] {Nx1 column vector}\n\t// Ax = b is equivalent to the condition that all data points lie on a sphere of radius R, centered at (cx,cy,cz). Hence,\n\t// by solving Ax = b for x in a least squares sense, we are implicitly solving for the values of cx, cy, cz and R for\n\t// which the corresponding sphere most closely fits the data. We perform a mean shift on the data for numerical\n\t// conditioning and stability reasons.\n\t\n\t// Declare variables\n\tsize_t N = P.size();\n\tEigen::MatrixXd A(N, 4);\n\tEigen::VectorXd b(N);\n\t\n\t// Calculate the mean of the data points\n\tEigen::Vector3d mean = Eigen::Vector3d::Zero();\n\tif(N >= 1)\n\t\tmean = std::accumulate(P.begin(), P.end(), mean) / N;\n\n\t// Construct the linear equation to solve (Ax = b)\n\tfor(size_t i = 0; i < N; i++)\n\t{\n\t\tconst Eigen::Vector3d p = P[i] - mean;\n\t\tA(i, 0) = p.x();\n\t\tA(i, 1) = p.y();\n\t\tA(i, 2) = p.z();\n\t\tA(i, 3) = 1;\n\t\tb(i) = p.squaredNorm();\n\t}\n\n\t// Find the least squares solution to Ax = b using Singular Value Decomposition (linear least squares fitting)\n\tEigen::VectorXd coefficients = A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);\n\n\t// Extract the centre and radius of the fitted sphere\n\tcentre = 0.5*coefficients.head<3>();\n\tradius = sqrt(coefficients(3) + centre.squaredNorm());\n\n\t// Correct for the applied mean shift\n\tcentre += mean;\n}\n\n// Fit a sphere of known centre to 3D data\nvoid ConicFit::fitSphereCentred(const Points3D& P, const Eigen::Vector3d& centre, double& radius)\n{\n\t// Suppose the i-th data point is (xi,yi,zi). The least squares solution to finding a sphere of radius R of known\n\t// centre (cx,cy,cz) that best fits the data points has a simple algebraic solution, given by:\n\t// R = sqrt(sum((xi-cx)^2 + (yi-cy)^2 + (zi-cz)^2, 1, N) / N)\n\t// In other words, the radius of best fit is the quadratic mean of the distances from the known centre to each point.\n\t\n\t// Declare variables\n\tsize_t N = P.size();\n\t\n\t// Calculate the radius of best fit\n\tdouble Rsq = 0.0;\n\tfor(size_t i = 0; i < N; i++)\n\t\tRsq += (P[i] - centre).squaredNorm() / N;\n\tradius = sqrt(Rsq);\n}\n\n// Calculate the fitting error of a sphere to certain 3D data (average distance to the sphere in units of sphere radii)\ndouble ConicFit::fitSphereError(const Points3D& P, const Eigen::Vector3d& centre, double radius)\n{\n\t// Calculate and return the required dimensionless fitting error\n\tdouble err = 0.0;\n\tsize_t N = P.size();\n\tif(radius != 0.0)\n\t{\n\t\tfor(size_t i = 0; i < N; i++)\n\t\t\terr += fabs((P[i] - centre).norm()/radius - 1.0)/N;\n\t}\n\telse\n\t{\n\t\tfor(size_t i = 0; i < N; i++)\n\t\t\terr += fabs((P[i] - centre).norm())/N;\n\t}\n\treturn err;\n}\n\n//\n// Ellipsoid fitting\n//\n\n// Fit an ellipsoid to 3D data\nvoid ConicFit::fitEllipsoid(const Points3D& P, Eigen::Vector3d& centre, Eigen::Matrix3d& coeff)\n{\n\t// We first compute the mean point (xm,ym,zm) of the data points, and bias the data points by the negative of this, resulting in zero mean data.\n\t// Suppose that the zero mean set of points is (xi,yi,zi). We then fit the following equation by least squares:\n\t// ax^2 + by^2 + cz^2 + 2dxy + 2exz + 2fyz + 2gx + 2hy + 2iz = 1\n\t// We do this by expressing the least squares fitting problem as the matrix equation Dv = y, where:\n\t// D = N rows of [xi^2 yi^2 zi^2 2*xi*yi 2*xi*zi 2*yi*zi 2*xi 2*yi 2*zi] {Nx9 matrix}\n\t// v = [a; b; c; d; e; f; g; h; i] {9x1 column vector}\n\t// y = N rows of [1] {Nx1 column vector}\n\t// The centre of the ellipsoid is at the point where the gradient of the defining function is zero. Therefore, accounting for (xm,ym,zm):\n\t// [cx; cy; cz] = [xm; ym; zm] - [a d e; d b f; e f c] \\ [g; h; i] {Matlab style}\n\t// (cx,cy,cz) is the centre of the ellipsoid of best fit through the original data points. The coefficient matrix is then computed by fitting an\n\t// ellipsoid of known centre (cx,cy,cz) through the data points. If A is the resulting coefficient matrix, the ellipsoid of best fit is:\n\t// (x-c)'A(x-c) = 1\n\t// where x = [x; y; z] and c = [cx; cy; cz] are column vectors.\n\t\n\t// Declare variables\n\tsize_t N = P.size();\n\tEigen::MatrixXd D(N, 9);\n\tEigen::VectorXd y(N);\n\t\n\t// Calculate the mean of the data points\n\tEigen::Vector3d mean = Eigen::Vector3d::Zero();\n\tif(N >= 1)\n\t\tmean = std::accumulate(P.begin(), P.end(), mean) / N;\n\t\n\t// Construct the linear equation to solve (Dv = y)\n\tfor(size_t i = 0; i < N; i++)\n\t{\n\t\tconst Eigen::Vector3d p = P[i] - mean;\n\t\tD(i, 0) = p.x()*p.x();\n\t\tD(i, 1) = p.y()*p.y();\n\t\tD(i, 2) = p.z()*p.z();\n\t\tD(i, 3) = 2.0*p.x()*p.y();\n\t\tD(i, 4) = 2.0*p.x()*p.z();\n\t\tD(i, 5) = 2.0*p.y()*p.z();\n\t\tD(i, 6) = 2.0*p.x();\n\t\tD(i, 7) = 2.0*p.y();\n\t\tD(i, 8) = 2.0*p.z();\n\t\ty(i) = 1.0;\n\t}\n\t\n\t// Find the least squares solution to Dv = y using Singular Value Decomposition (linear least squares fitting)\n\tEigen::VectorXd vhat = D.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(y);\n\t\n\t// Construct the coefficient matrix and vector\n\tEigen::Matrix3d A;\n\tA << vhat(0), vhat(3), vhat(4),\n\t vhat(3), vhat(1), vhat(5),\n\t vhat(4), vhat(5), vhat(2);\n\tEigen::Vector3d b(vhat(6), vhat(7), vhat(8));\n\t\n\t// Calculate the centre of the fitted ellipse\n\tcentre = mean - A.colPivHouseholderQr().solve(b);\n\t\n\t// Compute the coefficient matrix of the ellipsoid of best fit through the nominated centre\n\tfitEllipsoidCentred(P, centre, coeff);\n}\n\n// Fit an ellipsoid of known centre to 3D data\nvoid ConicFit::fitEllipsoidCentred(const Points3D& P, const Eigen::Vector3d& centre, Eigen::Matrix3d& coeff)\n{\n\t// We first bias the data to be relative to the centre (cx,cy) of the ellipsoid to fit. We then fit the following equation by least squares:\n\t// ax^2 + by^2 + cz^2 + 2dxy + 2exz + 2fyz = 1\n\t// If we define A = [a d e; d b f; e f c] as the coefficient matrix, and let xc = [x; y; z] then this is equivalent to:\n\t// xc'*A*xc = 1\n\t// Suppose that the i-th data point of biased data is (xi,yi,zi). We perform the ellipsoid fit by expressing the least squares fitting problem\n\t// as the matrix equation Dv = y, where:\n\t// D = N rows of [xi^2 yi^2 zi^2 2*xi*yi 2*xi*zi 2*yi*zi] {Nx6 matrix}\n\t// v = [a; b; c; d; e; f] {6x1 column vector}\n\t// y = N rows of [1] {Nx1 column vector}\n\t// The coefficient matrix A can be constructed from the solution v, after which the equation of the ellipsoid of best fit through the original\n\t// data becomes:\n\t// (x-c)'A(x-c) = 1\n\t// where x = [x; y; z] and c = [cx; cy; cz] are column vectors, and c is the specified centre of the ellipsoid.\n\t\n\t// Declare variables\n\tsize_t N = P.size();\n\tEigen::MatrixXd D(N, 6);\n\tEigen::VectorXd y(N);\n\t\n\t// Construct the linear equation to solve (Dv = y)\n\tfor(size_t i = 0; i < N; i++)\n\t{\n\t\tconst Eigen::Vector3d p = P[i] - centre;\n\t\tD(i, 0) = p.x()*p.x();\n\t\tD(i, 1) = p.y()*p.y();\n\t\tD(i, 2) = p.z()*p.z();\n\t\tD(i, 3) = 2.0*p.x()*p.y();\n\t\tD(i, 4) = 2.0*p.x()*p.z();\n\t\tD(i, 5) = 2.0*p.y()*p.z();\n\t\ty(i) = 1.0;\n\t}\n\t\n\t// Find the least squares solution to Dv = y using Singular Value Decomposition (linear least squares fitting)\n\tEigen::VectorXd vhat = D.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(y);\n\t\n\t// Construct the coefficient matrix\n\tcoeff << vhat(0), vhat(3), vhat(4),\n\t vhat(3), vhat(1), vhat(5),\n\t vhat(4), vhat(5), vhat(2);\n}\n\n// Calculate the fitting error of an ellipsoid to certain 3D data (average distance of normalised points to the unit sphere)\ndouble ConicFit::fitEllipsoidErrorCoeff(const Points3D& P, const Eigen::Vector3d& centre, const Eigen::Matrix3d& coeff)\n{\n\t// Declare variables\n\tEigen::Matrix3d rotmat, transform;\n\tEigen::Vector3d radii;\n\t\n\t// Calculate the transformation matrix\n\tdouble failed = (double) P.size();\n\tif(!ellipsoidMatrixToAxes(coeff, rotmat, radii)) return failed;\n\tif(!ellipsoidAxesToTransform(rotmat, radii, transform)) return failed;\n\t\n\t// Calculate the fitting error based on the centre and transformation matrix\n\treturn fitEllipsoidError(P, centre, transform);\n}\n\n// Calculate the fitting error of an ellipsoid to certain 3D data (average distance of normalised points to the unit sphere)\ndouble ConicFit::fitEllipsoidError(const Points3D& P, const Eigen::Vector3d& centre, const Eigen::Matrix3d& transform)\n{\n\t// Calculate and return the required dimensionless fitting error\n\tdouble err = 0.0;\n\tsize_t N = P.size();\n\tfor(size_t i = 0; i < N; i++)\n\t\terr += fabs((transform*(P[i] - centre)).norm() - 1.0)/N;\n\treturn err;\n}\n\n//\n// Ellipse functions\n//\n\n// Calculate the rotation matrix, radii and rotation angle of an ellipse defined by a coefficient matrix\nbool ConicFit::ellipseMatrixToAxes(const Eigen::Matrix2d& coeff, Eigen::Matrix2d& rotmat, Eigen::Vector2d& radii, double& angle)\n{\n\t// If the input coefficient matrix (coeff) is A, the output rotation matrix (rotmat) is Q, and the output radii (radii) are R,\n\t// then if we let D = diag(1./R.^2), the outputs of this function are constructed so that A = QDQ', Q^-1 = Q', |Q| = 1 and R > 0.\n\t// The angle is expressed as the magnitude of the rotation Q as a counterclockwise rotation.\n\t\n\t// Ensure the coefficient matrix is symmetric (trust the lower triangle)\n\tEigen::Matrix2d A = coeff;\n\tA(0,1) = A(1,0);\n\t\n\t// Compute the eigendecomposition of the coefficient matrix (the solver assumes the matrix is symmetric and trusts the lower triangle)\n\tEigen::SelfAdjointEigenSolver ES(A);\n\t\n\t// Retrieve the eigenvalues\n\tEigen::Vector2d lambda = ES.eigenvalues();\n\t\n\t// Check and ensure that the eigenvalues are not negative\n\tfor(size_t i = 0; i < 2; i++)\n\t{\n\t\tif(lambda(i) < -ZeroTol) return false;\n\t\tif(lambda(i) < 0.0) lambda(i) = 0.0;\n\t}\n\t\n\t// Retrieve the eigenvectors (columns of the matrix Q)\n\tEigen::Matrix2d Q = ES.eigenvectors();\n\t\n\t// Ensure that the eigenvectors are unit norm\n\tfor(size_t i = 0; i < 2; i++)\n\t{\n\t\tdouble norm = Q.col(i).norm();\n\t\tif(norm < ZeroTol) return false;\n\t\tQ.col(i) /= norm;\n\t}\n\t\n\t// Enforce the right hand rule for the eigenvectors\n\tif(Q.determinant() < 0.0)\n\t\tQ.col(1) = -Q.col(1);\n\t\n\t// Transcribe the rotation matrix of the ellipse\n\trotmat = Q;\n\t\n\t// Calculate the radii of the ellipse\n\tradii.x() = 1.0 / sqrt(lambda.x());\n\tradii.y() = 1.0 / sqrt(lambda.y());\n\t\n\t// Calculate the angle of the ellipse\n\tangle = atan2(rotmat(1,0) + rotmat(1,1), rotmat(0,0) + rotmat(0,1)) - M_PI/4.0;\n\tif(angle <= -M_PI)\n\t\tangle += 2.0*M_PI;\n\t\n\t// Return success\n\treturn true;\n}\n\n// Calculate the normalisation transformation matrix of an ellipse defined by its rotation matrix and radii\nbool ConicFit::ellipseAxesToTransform(const Eigen::Matrix2d& rotmat, const Eigen::Vector2d& radii, Eigen::Matrix2d& transform)\n{\n\t// If the input rotation matrix (rotmat) is Q, the input radii (radii) are R, and the output normalisation matrix (transform) is W,\n\t// then the corresponding coefficient matrix is A = QDQ' where D = diag(1./R.^2). The normalisation matrix is then the positive\n\t// definite symmetric solution to W*W = A (i.e. W = sqrtm(A)).\n\t\n\t// Check that none of the radii are negative or zero\n\tif(radii.x() <= 0.0 || radii.y() <= 0.0) return false;\n\t\n\t// Construct the required normalisation transformation matrix\n\tEigen::Vector2d rootLambda(1.0/radii.x(), 1.0/radii.y());\n\ttransform = rotmat * rootLambda.asDiagonal() * rotmat.inverse();\n\t\n\t// Return success\n\treturn true;\n}\n\n//\n// Ellipsoid functions\n//\n\n// Calculate the rotation matrix and radii of an ellipsoid defined by a coefficient matrix\nbool ConicFit::ellipsoidMatrixToAxes(const Eigen::Matrix3d& coeff, Eigen::Matrix3d& rotmat, Eigen::Vector3d& radii)\n{\n\t// If the input coefficient matrix (coeff) is A, the output rotation matrix (rotmat) is Q, and the output radii (radii) are R,\n\t// then if we let D = diag(1./R.^2), the outputs of this function are constructed so that A = QDQ', Q^-1 = Q', |Q| = 1 and R > 0.\n\t\n\t// Ensure the coefficient matrix is symmetric (trust the lower triangle)\n\tEigen::Matrix3d A = coeff;\n\tA(0,1) = A(1,0);\n\tA(0,2) = A(2,0);\n\tA(1,2) = A(2,1);\n\t\n\t// Compute the eigendecomposition of the coefficient matrix (the solver assumes the matrix is symmetric and trusts the lower triangle)\n\tEigen::SelfAdjointEigenSolver ES(A);\n\t\n\t// Retrieve the eigenvalues\n\tEigen::Vector3d lambda = ES.eigenvalues();\n\t\n\t// Check and ensure that the eigenvalues are not negative\n\tfor(size_t i = 0; i < 3; i++)\n\t{\n\t\tif(lambda(i) < -ZeroTol) return false;\n\t\tif(lambda(i) < 0.0) lambda(i) = 0.0;\n\t}\n\t\n\t// Retrieve the eigenvectors (columns of the matrix Q)\n\tEigen::Matrix3d Q = ES.eigenvectors();\n\t\n\t// Ensure that the eigenvectors are unit norm\n\tfor(size_t i = 0; i < 3; i++)\n\t{\n\t\tdouble norm = Q.col(i).norm();\n\t\tif(norm < ZeroTol) return false;\n\t\tQ.col(i) /= norm;\n\t}\n\t\n\t// Enforce the right hand rule for the eigenvectors\n\tif(Q.determinant() < 0.0)\n\t\tQ.col(2) = -Q.col(2);\n\t\n\t// Transcribe the rotation matrix of the ellipsoid\n\trotmat = Q;\n\t\n\t// Calculate the radii of the ellipsoid\n\tradii.x() = 1.0 / sqrt(lambda.x());\n\tradii.y() = 1.0 / sqrt(lambda.y());\n\tradii.z() = 1.0 / sqrt(lambda.z());\n\t\n\t// Return success\n\treturn true;\n}\n\n// Calculate the normalisation transformation matrix of an ellipsoid defined by its rotation matrix and radii\nbool ConicFit::ellipsoidAxesToTransform(const Eigen::Matrix3d& rotmat, const Eigen::Vector3d& radii, Eigen::Matrix3d& transform)\n{\n\t// If the input rotation matrix (rotmat) is Q, the input radii (radii) are R, and the output normalisation matrix (transform) is W,\n\t// then the corresponding coefficient matrix is A = QDQ' where D = diag(1./R.^2). The normalisation matrix is then the positive\n\t// definite symmetric solution to W*W = A (i.e. W = sqrtm(A)).\n\t\n\t// Check that none of the radii are negative or zero\n\tif(radii.x() <= 0.0 || radii.y() <= 0.0 || radii.z() <= 0.0) return false;\n\t\n\t// Construct the required normalisation transformation matrix\n\tEigen::Vector3d rootLambda(1.0/radii.x(), 1.0/radii.y(), 1.0/radii.z());\n\ttransform = rotmat * rootLambda.asDiagonal() * rotmat.inverse();\n\t\n\t// Return success\n\treturn true;\n}\n\n//\n// Conic data generation functions\n//\n\n// Generate circle data (returns N points)\nvoid ConicFit::genCircleData(ConicFit::Points2D& P, size_t N, const Eigen::Vector2d& centre, double radius)\n{\n\t// Generate the required data\n\tP.clear();\n\tif(N < 3) N = 3;\n\tEigen::Vector2d tmp;\n\tfor(size_t i = 0; i < N; i++)\n\t{\n\t\tdouble t = i * (4.0*M_PI / (N - 1));\n\t\ttmp << radius*cos(t), radius*sin(t);\n\t\ttmp += centre;\n\t\tP.push_back(tmp);\n\t}\n}\n\n// Generate ellipse data (returns N points)\nvoid ConicFit::genEllipseData(ConicFit::Points2D& P, size_t N, const Eigen::Vector2d& centre, const Eigen::Vector2d& radii, double angle)\n{\n\t// Generate the required data\n\tP.clear();\n\tif(N < 3) N = 3;\n\tEigen::Vector2d tmp;\n\tEigen::Matrix2d rotmat;\n\tdouble cangle = cos(angle);\n\tdouble sangle = sin(angle);\n\trotmat << cangle, -sangle, sangle, cangle;\n\tfor(size_t i = 0; i < N; i++)\n\t{\n\t\tdouble t = i * (4.0*M_PI / (N - 1));\n\t\ttmp << radii.x()*cos(t), radii.y()*sin(t);\n\t\ttmp = rotmat * tmp;\n\t\ttmp += centre;\n\t\tP.push_back(tmp);\n\t}\n}\n\n// Generate sphere data (returns N^2 points)\nvoid ConicFit::genSphereData(ConicFit::Points3D& PP, size_t N, const Eigen::Vector3d& centre, double radius)\n{\n\t// Generate the required data\n\tPP.clear();\n\tif(N < 3) N = 3;\n\tEigen::Vector3d tmp;\n\tfor(size_t i = 0; i < N; i++)\n\t{\n\t\tdouble u = i * (2.0*M_PI / (N - 1));\n\t\tfor(size_t j = 0; j < N; j++)\n\t\t{\n\t\t\tdouble v = j * (M_PI / (N - 1));\n\t\t\ttmp << radius*cos(u)*sin(v), radius*sin(u)*sin(v), radius*cos(v);\n\t\t\ttmp += centre;\n\t\t\tPP.push_back(tmp);\n\t\t}\n\t}\n}\n\n// Generate ellipsoid data (returns N^2 points)\nvoid ConicFit::genEllipsoidData(ConicFit::Points3D& PP, size_t N, const Eigen::Vector3d& centre, const Eigen::Vector3d& radii, const Eigen::Matrix3d& rotmat)\n{\n\t// Generate the required data\n\tPP.clear();\n\tif(N < 3) N = 3;\n\tEigen::Vector3d tmp;\n\tfor(size_t i = 0; i < N; i++)\n\t{\n\t\tdouble u = i * (2.0*M_PI / (N - 1));\n\t\tfor(size_t j = 0; j < N; j++)\n\t\t{\n\t\t\tdouble v = j * (M_PI / (N - 1));\n\t\t\ttmp << radii.x()*cos(u)*sin(v), radii.y()*sin(u)*sin(v), radii.z()*cos(v);\n\t\t\ttmp = rotmat * tmp;\n\t\t\ttmp += centre;\n\t\t\tPP.push_back(tmp);\n\t\t}\n\t}\n}\n// EOF", "meta": {"hexsha": "419d654b51320c3ddc991528afa8c611dfd7554a", "size": 38848, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nimbro_robotcontrol/util/rc_utils/src/conicfit.cpp", "max_stars_repo_name": "hfarazi/humanoid_op_ros_kinetic", "max_stars_repo_head_hexsha": "84712bd541d0130b840ad1935d5bfe301814dbe6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2015-11-04T01:29:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T05:37:42.000Z", "max_issues_repo_path": "src/nimbro_robotcontrol/util/rc_utils/src/conicfit.cpp", "max_issues_repo_name": "hfarazi/humanoid_op_ros_kinetic", "max_issues_repo_head_hexsha": "84712bd541d0130b840ad1935d5bfe301814dbe6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-22T08:34:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-22T08:34:34.000Z", "max_forks_repo_path": "src/nimbro_robotcontrol/util/rc_utils/src/conicfit.cpp", "max_forks_repo_name": "hfarazi/humanoid_op_ros_kinetic", "max_forks_repo_head_hexsha": "84712bd541d0130b840ad1935d5bfe301814dbe6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2016-03-05T14:28:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:50:47.000Z", "avg_line_length": 35.5750915751, "max_line_length": 182, "alphanum_fraction": 0.6568677924, "num_tokens": 12295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012762876286, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7981570724754793}} {"text": "/**\n * @file eigen_quaternion.cpp\n * @author Maximilian Harr \n * @date 17.06.2017\n *\n * @brief Eigen quaternion computations\n *\n *\n *\n * Coding Standard:\n * wiki.ros.org/CppStyleGuide\n * https://google.github.io/styleguide/cppguide.html\n *\n *\n * @bug\n *\n *\n * @todo\n *\n *\n */\n\n// PRAGMA\n\n// SYSTEM INCLUDES\n#include /* Header that defines the standard input/output stream objects */\n#include /* Header that defines several general purpose functions */\n#include \n#include /* template library for linear algebra http://eigen.tuxfamily.org */\n#include /* Defines M_PI for pi value */\n#include \n#include \n\n// PROJECT INCLUDES\n\n// LOCAL INCLUDES\n\n// FORWARD REFERENCES\n\n// FUNCTION PROTOTYPES\n\n/** @brief Standard command line parameter processing.\n * @param Pass command line parameters\n * @return 0 if -h flag is set\n */\nint cmd_check(int, char*[]);\n\n// GLOBAL VARIABLES\n\n\nusing namespace Eigen;\nusing namespace std;\n\nvoid outputAsMatrix(const Eigen::Quaterniond& q)\n{\n std::cout << \"R=\" << std::endl << q.normalized().toRotationMatrix() << std::endl;\n}\n\n//// MAIN //////////////////////////////////////////////////////////////////////////////////////////\nint main(int argc, char* argv[])\n{\n /* Check command line options. Stop execution if -h is set. */\n if(!cmd_check(argc,argv)) return 0;\n\n /* Specify roation axis and angle */\n Eigen::Vector3d rotation_axis{0, 0, 1};\n Eigen::Vector3d pose{0, 0, 1};\n double angle = 0;\n if(argc == 2){\n angle = atof(argv[1]);}\n else{\n angle = M_PI/8.0;\n }\n\n /* Compute Quaternion by hand */\n auto sinA = std::sin(angle / 2);\n auto cosA = std::cos(angle / 2);\n Eigen::Quaterniond q;\n q.x() = rotation_axis(0) * sinA;\n q.y() = rotation_axis(1) * sinA;\n q.z() = rotation_axis(2) * sinA;\n q.w() = cosA;\n\n /* Let Eigen compute Quaternion (use Vector3d::UnitZ() instead of rotation_axis) */\n Eigen::Quaterniond q2 = Eigen::Quaterniond{ Eigen::AngleAxisd{ angle, rotation_axis } };\n\n /* Compare rotation matrices */\n outputAsMatrix( q );\n outputAsMatrix( q2 );\n\n /* Get rotation matrix from quaternion */\n Matrix3d m; \n m = Eigen::Quaterniond(q2); \n std::cout << \"Quaternion q2: \" << std::endl << q2.x() << std::endl\n << q2.y() << std::endl << q2.z() << std::endl << q2.w() << std::endl;\n std::cout << \"Rotation matrix m of Quaternion q2: \" << std::endl << m << std::endl;\n\n /* Multiplication of quaternions */\n Matrix3d m2;\n m2 = Eigen::Quaterniond(q2*q2);\n std::cout << \"m*m: \" << std::endl << m*m << std::endl;\n std::cout << \"Rotation matrix of q2*q2: \" << std::endl << m2 << std::endl;\n\n /* Dividing Quaternions */\n Matrix3d m3;\n m3 = Eigen::Quaterniond(q2.inverse());\n std::cout << \"m.inverse(): \" << std::endl << m.inverse() << std::endl;\n std::cout << \"Rotation matrix of q2.inverse(): \" << std::endl << m3 << std::endl;\n\n /* Rotate Vector */\n Eigen::Vector3d x_axis = Eigen::Vector3d::UnitX();\n std::cout << \"q2*x_axis: \" << std::endl << q2*x_axis << std::endl;\n \n /* Get rotation axis of Quaternion */\n Eigen::AngleAxisd rot_axis_m(m);\n Eigen::AngleAxisd rot_axis_q2(q2);\n rot_axis_m.axis().cross(rot_axis_q2.axis());\n std::cout << \"Rotation axis of m: \" << std::endl << rot_axis_m.axis() << std::endl;\n std::cout << \"Rotation axis of q2: \" << std::endl << rot_axis_q2.axis() << std::endl;\n\n /* Get Euler Angles from Quaternion */\n Eigen::Vector3d euler = q2.toRotationMatrix().eulerAngles(0,1,2);\n std::cout << \"Euler angles yf q2: \" << std::endl << euler << std::endl;\n\n /* Get Quaternion from euler angles */\n Eigen::Quaterniond q3;\n q3 = AngleAxisd(euler[0], Eigen::Vector3d::UnitX())*\n AngleAxisd(euler[1], Eigen::Vector3d::UnitY())*\n AngleAxisd(euler[2], Eigen::Vector3d::UnitZ());\n std::cout << \"q3 from euler angles: \" << std::endl << q3.x() << std::endl\n << q3.y() << std::endl << q3.z() << std::endl << q3.w() << std::endl;\n \n /* Rotate covariance matrix */\n Eigen::MatrixXd covariance_q = Eigen::MatrixXd::Zero(3,3);\n Eigen::Quaterniond q4 = Eigen::Quaterniond{ Eigen::AngleAxisd{ angle, Eigen::Vector3d::UnitZ() } };\n Eigen::MatrixXd covariance_r = Eigen::MatrixXd::Zero(3,3);\n Matrix3d rotation;\n rotation = Eigen::AngleAxisd{ Eigen::AngleAxisd( angle, Eigen::Vector3d::UnitZ()) };\n\n covariance_q(0,0) = 1;\n covariance_q(1,1) = 2;\n covariance_q(2,2) = 3;\n covariance_r(0,0) = 1;\n covariance_r(1,1) = 2;\n covariance_r(2,2) = 3;\n\n covariance_q = q * covariance_q; // Rotate covariance matrix in lane coordinates\n covariance_q = covariance_q*covariance_q.transpose();\n covariance_r = rotation*covariance_r*covariance_r.transpose()*rotation.transpose();\n\n std::cout << \"covariance_q:\\n \" << covariance_q << std::endl;\n std::cout << \"covariance_r:\\n \" << covariance_r << std::endl;\n\n\n}\n\n\n//// FUNCTION DEFINITIONS //////////////////////////////////////////////////////////////////////////\nint cmd_check(int argc, char* argv[])\n{\n int option;\n /* third argument of getopt specifies valid options and whether they need input(:) */\n while((option = getopt(argc,argv,\"hp:\"))>=0)\n {\n switch (option)\n {\n case 'h': std::cout\n << \"Usage: [options] \\n\\n\"\n << \" \\n\\n\"\n << \"Options: \\n\"\n << \" -h show this help message and exit \\n\"\n << \" -p \\n\"\n << \" \\n\";\n return 0; /* do not execute main with this option */\n case 'p': std::cout << \"-p = \" << optarg << \"\\n\"; /* optarg is option argument */\n break;\n }\n }\n return 1;\n}\n\n\n", "meta": {"hexsha": "526bf4801afc89599dbba574b9694be81f11d18a", "size": 5745, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/cpp_libs/src/eigen_quaternion.cpp", "max_stars_repo_name": "maximilianharr/code_snippets", "max_stars_repo_head_hexsha": "8b271e6fa9174e24200e88be59e417abd5f2f59a", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/cpp_libs/src/eigen_quaternion.cpp", "max_issues_repo_name": "maximilianharr/code_snippets", "max_issues_repo_head_hexsha": "8b271e6fa9174e24200e88be59e417abd5f2f59a", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/cpp_libs/src/eigen_quaternion.cpp", "max_forks_repo_name": "maximilianharr/code_snippets", "max_forks_repo_head_hexsha": "8b271e6fa9174e24200e88be59e417abd5f2f59a", "max_forks_repo_licenses": ["BSD-3-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.393442623, "max_line_length": 101, "alphanum_fraction": 0.5942558747, "num_tokens": 1646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.8577681013541611, "lm_q1q2_score": 0.7981174145127462}} {"text": "#include \r\n#include \r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\nint main()\r\n{\r\n Matrix2f A;\r\n A << 1, 2, 2, 3;\r\n cout << \"Here is the matrix A:\\n\" << A << endl;\r\n SelfAdjointEigenSolver eigensolver(A);\r\n if (eigensolver.info() != Success) abort();\r\n cout << \"The eigenvalues of A are:\\n\" << eigensolver.eigenvalues() << endl;\r\n cout << \"Here's a matrix whose columns are eigenvectors of A \\n\"\r\n << \"corresponding to these eigenvalues:\\n\"\r\n << eigensolver.eigenvectors() << endl;\r\n}\r\n", "meta": {"hexsha": "33bfa77f91688e0d9d2b19acde564ff676ccdcb4", "size": 552, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/TutorialLinAlgSelfAdjointEigenSolver.cpp", "max_stars_repo_name": "k4rth33k/dnnc-operators", "max_stars_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T14:35:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-11T23:59:22.000Z", "max_issues_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/TutorialLinAlgSelfAdjointEigenSolver.cpp", "max_issues_repo_name": "k4rth33k/dnnc-operators", "max_issues_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-08-12T04:38:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T16:32:13.000Z", "max_forks_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/TutorialLinAlgSelfAdjointEigenSolver.cpp", "max_forks_repo_name": "k4rth33k/dnnc-operators", "max_forks_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-08-15T13:29:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-09T17:08:04.000Z", "avg_line_length": 29.0526315789, "max_line_length": 79, "alphanum_fraction": 0.6213768116, "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7980460639853924}} {"text": "#include \"ode45.hpp\"\n\n#include \n#include \n\n#include \n#include \n\n//! \\file stabrk.cpp Solution for Problem 1, PS13, involving ode45 and matrix ODEs\n\n//! \\brief Solve matrix IVP Y' = -(Y-Y')*Y using ode45 up to time T\n//! \\param[in] Y0 Initial data Y(0) (as matrix)\n//! \\param[in] T final time of simulation\n//! \\return Matrix of solution of IVP at t = T\nEigen::MatrixXd matode(const Eigen::MatrixXd & Y0, double T) {\n // TODO: evolve Y0 up to T using ode45 (read ode45.hpp)\n}\n\n//! \\brief Find if invariant is preserved after evolution with matode\n//! \\param[in] Y0 Initial data Y(0) (as matrix)\n//! \\param[in] T final time of simulation\n//! \\return true if invariant was preserved (up to round-off), i.e. if norm was less than 10*eps\nbool checkinvariant(const Eigen::MatrixXd & M, double T) {\n // TODO: check if invariant is preserved applying matode\n}\n\n//! \\brief Implement ONE step of explicit Euler applied to Y0, of ODE Y' = A*Y\n//! \\param[in] A matrix A of the ODE\n//! \\param[in] Y0 Initial state\n//! \\param[in] h step size\n//! \\return next step\nEigen::MatrixXd expeulstep(const Eigen::MatrixXd & A, const Eigen::MatrixXd & Y0, double h) {\n // TODO: ose step of EE\n}\n\n//! \\brief Implement ONE step of implicit Euler applied to Y0, of ODE Y' = A*Y\n//! \\param[in] A matrix A of the ODE\n//! \\param[in] Y0 Initial state\n//! \\param[in] h step size\n//! \\return next step\nEigen::MatrixXd impeulstep(const Eigen::MatrixXd & A, const Eigen::MatrixXd & Y0, double h) {\n // TODO: ose step of IE\n}\n\n//! \\brief Implement ONE step of implicit midpoint ruler applied to Y0, of ODE Y' = A*Y\n//! \\param[in] A matrix A of the ODE\n//! \\param[in] Y0 Initial state\n//! \\param[in] h step size\n//! \\return next step\nEigen::MatrixXd impstep(const Eigen::MatrixXd & A, const Eigen::MatrixXd & Y0, double h) {\n // TODO: ose step of IMP\n}\n\nint main() {\n \n double T = 1;\n unsigned int n = 3;\n \n Eigen::MatrixXd M(n,n);\n M << 8,1,6,3,5,7,4,9,2;\n \n std::cout << \"SUBTASK 1. c)\" << std::endl;\n // Test preservation of orthogonality\n \n // Build Q\n Eigen::HouseholderQR qr(M.rows(), M.cols());\n qr.compute(M);\n Eigen::MatrixXd Q = qr.householderQ();\n \n // Build A\n Eigen::MatrixXd A(n,n);\n A << 0, 1, 1, -1, 0, 1, -1, -1, 0;\n Eigen::MatrixXd I = Eigen::MatrixXd::Identity(n,n);\n \n // TODO: compute norm of Y'Y-I for 20 steps and print table\n \n std::cout << \"SUBTASK 1. d)\" << std::endl;\n // Test implementation of ode45\n \n // TODO: TEST matode\n \n std::cout << \"SUBTASK 1. g)\" << std::endl;\n // Test whether invariant was preserved or not\n \n // TODO: TEST if matode preserves invariant using checkinvariant\n \n \n return 0;\n}\n", "meta": {"hexsha": "996c03f6a8f39972dd837be1d5c89e0844a8fcbf", "size": 2770, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS13/templates_ps13/matrix_ode_template.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS13/templates_ps13/matrix_ode_template.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS13/templates_ps13/matrix_ode_template.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7777777778, "max_line_length": 96, "alphanum_fraction": 0.6357400722, "num_tokens": 826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8918110555020056, "lm_q1q2_score": 0.7979831382169844}} {"text": "#include \n#include \n#include \"timer.h\"\n\nusing namespace Eigen;\nusing namespace std;\n\n// WARNING: Global! Timer variable\ntimer<> tm_slow, tm_fast;\n\n//! \\brief Compute lmin from the vector d, naive implementation\n//! \\param[in] d VectorXd of size $n$\n//! \\param[in] double tol, tolerance\n//! \\param[out] double lmin\n\nvoid rankoneinvit(const VectorXd & d, const double & tol, double & lmin)\n{\n VectorXd ev=d;\n lmin=0;\n double lnew=d.cwiseAbs().minCoeff();\n while (abs(lnew-lmin)>tol*lmin) {\n tm_slow.start();\n lmin=lnew;\n MatrixXd M=d.asDi agonal();\n M+=ev*ev.transpose();\n ev = M.lu().solve(ev);\n ev.normalize();\n lnew=ev.transpose()*M*ev;\n tm_slow.stop();\n }\n lmin=lnew;\n}\n\n//! \\brief Compute lmin from the vector d, optimized implementation\n//! \\param[in] d VectorXd of size $n$\n//! \\param[in] double tol, tolerance\n//! \\param[out] double lmin\n\n \nvoid rankoneinvit_fast(const VectorXd & d, const double & tol, double & lmin)\n{\n VectorXd ev=d;\n lmin=0;\n double lnew=d.cwiseAbs().minCoeff();\n \n VectorXd dinv=(1/d.array()).matrix();\n while (abs(lnew-lmin)>tol*lmin) {\n tm_fast.start();\n lmin=lnew;\n VectorXd ev0=ev;\n \n VectorXd Aib=dinv.cwiseProduct(ev); // In these three lines we solve the linear system with the\n double temp=ev.transpose()*Aib; // Sherman-Morrison-Woodbury formula, in the case of rank-1\n ev=Aib*(1-temp/(1+temp)); // perturbations\n \n \n ev.normalize();\n lnew=ev.transpose()*d.cwiseProduct(ev)+pow(ev.transpose()*ev0,2); //better implementation\n tm_fast.stop();\n }\n lmin=lnew;\n}\n\n\n\nint main(){\n srand((unsigned int) time(0));\n double tol=1e-3;\n double lmin;\n int n=10;\n \n // Check correctedness of the fast version\n VectorXd d=VectorXd::Random(n);\n rankoneinvit(d,tol,lmin);\n cout<<\"lmin = \"<\n\n#include \n#include \n#include \n\n#include \n\nnamespace lgmath {\nnamespace se3 {\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 4x4 \"skew symmetric matrix\"\n///\n/// The hat (^) operator, builds the 4x4 skew symmetric matrix from the 3x1 axis angle\n/// vector and 3x1 translation vector.\n///\n/// hat(rho, aaxis) = [aaxis^ rho] = [0.0 -a3 a2 rho1]\n/// [ 0^T 0] [ a3 0.0 -a1 rho2]\n/// [-a2 a1 0.0 rho3]\n/// [0.0 0.0 0.0 0.0]\n///\n/// See eq. 4 in Barfoot-TRO-2014 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix4d hat(const Eigen::Vector3d& rho, const Eigen::Vector3d& aaxis) {\n\n Eigen::Matrix4d mat = Eigen::Matrix4d::Zero();\n mat.topLeftCorner<3,3>() = so3::hat(aaxis);\n mat.topRightCorner<3,1>() = rho;\n return mat;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 4x4 \"skew symmetric matrix\"\n///\n/// The hat (^) operator, builds the 4x4 skew symmetric matrix from\n/// the 6x1 se3 algebra vector, xi:\n///\n/// xi^ = [rho ] = [aaxis^ rho] = [0.0 -a3 a2 rho1]\n/// [aaxis] [ 0^T 0] [ a3 0.0 -a1 rho2]\n/// [-a2 a1 0.0 rho3]\n/// [0.0 0.0 0.0 0.0]\n///\n/// See eq. 4 in Barfoot-TRO-2014 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix4d hat(const Eigen::Matrix& xi) {\n\n return hat(xi.head<3>(), xi.tail<3>());\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 6x6 \"curly hat\" matrix (related to the skew symmetric matrix)\n///\n/// The curly hat operator builds the 6x6 skew symmetric matrix from the 3x1 axis angle\n/// vector and 3x1 translation vector.\n///\n/// curlyhat(rho, aaxis) = [aaxis^ rho^]\n/// [ 0 aaxis^]\n///\n/// See eq. 12 in Barfoot-TRO-2014 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix curlyhat(const Eigen::Vector3d& rho, const Eigen::Vector3d& aaxis) {\n\n Eigen::Matrix mat = Eigen::Matrix::Zero();\n mat.topLeftCorner<3,3>() = mat.bottomRightCorner<3,3>() = so3::hat(aaxis);\n mat.topRightCorner<3,3>() = so3::hat(rho);\n return mat;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 6x6 \"curly hat\" matrix (related to the skew symmetric matrix)\n///\n/// The curly hat operator builds the 6x6 skew symmetric matrix\n/// from the 6x1 se3 algebra vector, xi:\n///\n/// curlyhat(xi) = curlyhat([rho ]) = [aaxis^ rho^]\n/// ([aaxis]) [ 0 aaxis^]\n///\n/// See eq. 12 in Barfoot-TRO-2014 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix curlyhat(const Eigen::Matrix& xi) {\n\n return curlyhat(xi.head<3>(), xi.tail<3>());\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Turns a homogeneous point into a special 4x6 matrix\n///\n/// See eq. 72 in Barfoot-TRO-2014 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix point2fs(const Eigen::Vector3d& p, double scale) {\n\n Eigen::Matrix mat = Eigen::Matrix::Zero();\n mat.topLeftCorner<3,3>() = scale*Eigen::Matrix3d::Identity();\n mat.topRightCorner<3,3>() = -so3::hat(p);\n return mat;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Turns a homogeneous point into a special 6x4 matrix\n///\n/// See eq. 72 in Barfoot-TRO-2014 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix point2sf(const Eigen::Vector3d& p, double scale) {\n\n Eigen::Matrix mat = Eigen::Matrix::Zero();\n mat.bottomLeftCorner<3,3>() = -so3::hat(p);\n mat.topRightCorner<3,1>() = p;\n return mat;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds a transformation matrix using the analytical exponential map\n///\n/// This function builds a transformation matrix, T_ab, using the analytical exponential map,\n/// from the se3 algebra vector, xi_ba,\n///\n/// T_ab = exp(xi_ba^) = [ C_ab r_ba_ina], xi_ba = [ rho_ba]\n/// [ 0^T 1] [aaxis_ba]\n///\n/// where C_ab is a 3x3 rotation matrix from 'b' to 'a', r_ba_ina is the 3x1 translation\n/// vector from 'a' to 'b' expressed in frame 'a', aaxis_ba is a 3x1 axis-angle vector,\n/// the magnitude of the angle of rotation can be recovered by finding the norm of the vector,\n/// and the axis of rotation is the unit-length vector that arises from normalization.\n/// Note that the angle around the axis, aaxis_ba, is a right-hand-rule (counter-clockwise\n/// positive) angle from 'a' to 'b'.\n///\n/// The parameter, rho_ba, is a special translation-like parameter related to 'twist' theory.\n/// It is most inuitively described as being like a constant linear velocity (expressed in\n/// the smoothly-moving frame) for a fixed duration; for example, consider the curve of a\n/// car driving 'x' meters while turning at a rate of 'y' rad/s.\n///\n/// For more information see Barfoot-TRO-2014 Appendix B1.\n///\n/// Alternatively, we that note that\n///\n/// T_ba = exp(-xi_ba^) = exp(xi_ab^).\n///\n/// Both the analytical (numTerms = 0) or the numerical (numTerms > 0) may be evaluated.\n//////////////////////////////////////////////////////////////////////////////////////////////\nvoid vec2tran_analytical(const Eigen::Vector3d& rho_ba, const Eigen::Vector3d& aaxis_ba,\n Eigen::Matrix3d* out_C_ab, Eigen::Vector3d* out_r_ba_ina) {\n\n // Check pointers\n if (out_C_ab == NULL) {\n throw std::invalid_argument(\"Null pointer out_C_ab in vec2tran_analytical\");\n }\n if (out_r_ba_ina == NULL) {\n throw std::invalid_argument(\"Null pointer out_r_ba_ina in vec2tran_analytical\");\n }\n\n if(aaxis_ba.norm() < 1e-12) {\n\n // If angle is very small, rotation is Identity\n *out_C_ab = Eigen::Matrix3d::Identity();\n *out_r_ba_ina = rho_ba;\n } else {\n\n // Normal analytical solution\n Eigen::Matrix3d J_ab;\n\n // Use rotation identity involving jacobian, as we need it to\n // convert rho_ba to the proper translation\n so3::vec2rot(aaxis_ba, out_C_ab, &J_ab);\n\n // Convert rho_ba (twist-translation) to r_ba_ina\n *out_r_ba_ina = J_ab*rho_ba;\n }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds a transformation matrix using the first N terms of the infinite series\n///\n/// Builds a transformation matrix numerically using the infinite series evalation\n/// of the exponential map.\n///\n/// For more information see eq. 96 in Barfoot-TRO-2014\n//////////////////////////////////////////////////////////////////////////////////////////////\nvoid vec2tran_numerical(const Eigen::Vector3d& rho_ba, const Eigen::Vector3d& aaxis_ba,\n Eigen::Matrix3d* out_C_ab, Eigen::Vector3d* out_r_ba_ina,\n unsigned int numTerms) {\n\n // Check pointers\n if (out_C_ab == NULL) {\n throw std::invalid_argument(\"Null pointer out_C_ab in vec2tran_numerical\");\n }\n if (out_r_ba_ina == NULL) {\n throw std::invalid_argument(\"Null pointer out_r_ba_ina in vec2tran_numerical\");\n }\n\n // Init 4x4 transformation\n Eigen::Matrix4d T_ab = Eigen::Matrix4d::Identity();\n\n // Incremental variables\n Eigen::Matrix xi_ba; xi_ba << rho_ba, aaxis_ba;\n Eigen::Matrix4d x_small = se3::hat(xi_ba);\n Eigen::Matrix4d x_small_n = Eigen::Matrix4d::Identity();\n\n // Loop over sum up to the specified numTerms\n for (unsigned int n = 1; n <= numTerms; n++) {\n x_small_n = x_small_n*x_small/double(n);\n T_ab += x_small_n;\n }\n\n // Fill output\n *out_C_ab = T_ab.topLeftCorner<3,3>();\n *out_r_ba_ina = T_ab.topRightCorner<3,1>();\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 3x3 rotation and 3x1 translation using the exponential map, the\n/// default parameters (numTerms = 0) use the analytical solution.\n//////////////////////////////////////////////////////////////////////////////////////////////\nvoid vec2tran(const Eigen::Matrix& xi_ba, Eigen::Matrix3d* out_C_ab,\n Eigen::Vector3d* out_r_ba_ina, unsigned int numTerms) {\n\n if (numTerms == 0) {\n\n // Analytical solution\n vec2tran_analytical(xi_ba.head<3>(), xi_ba.tail<3>(), out_C_ab, out_r_ba_ina);\n } else {\n\n // Numerical solution (good for testing the analytical solution)\n vec2tran_numerical(xi_ba.head<3>(), xi_ba.tail<3>(), out_C_ab, out_r_ba_ina, numTerms);\n }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds a 4x4 transformation matrix using the exponential map, the\n/// default parameters (numTerms = 0) use the analytical solution.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix4d vec2tran(const Eigen::Matrix& xi_ba, unsigned int numTerms) {\n\n // Get rotation and translation\n Eigen::Matrix3d C_ab;\n Eigen::Vector3d r_ba_ina;\n vec2tran(xi_ba, &C_ab, &r_ba_ina, numTerms);\n\n // Fill output\n Eigen::Matrix4d T_ab = Eigen::Matrix4d::Identity();\n T_ab.topLeftCorner<3,3>() = C_ab;\n T_ab.topRightCorner<3,1>() = r_ba_ina;\n return T_ab;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Compute the matrix log of a transformation matrix (from the rotation and trans)\n///\n/// Compute the inverse of the exponential map (the logarithmic map). This lets us go from\n/// a the 3x3 rotation and 3x1 translation vector back to a 6x1 se3 algebra vector (composed\n/// of a 3x1 axis-angle vector and 3x1 twist-translation vector). In some cases, when the\n/// rotation in the transformation matrix is 'numerically off', this involves some\n/// 'projection' back to SE(3).\n///\n/// xi_ba = ln(T_ab)\n///\n/// where xi_ba is the 6x1 se3 algebra vector. Alternatively, we that note that\n///\n/// xi_ab = -xi_ba = ln(T_ba) = ln(T_ab^{-1})\n///\n/// See Barfoot-TRO-2014 Appendix B2 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix tran2vec(const Eigen::Matrix3d& C_ab,\n const Eigen::Vector3d& r_ba_ina) {\n\n // Init\n Eigen::Matrix xi_ba;\n\n // Get axis angle from rotation matrix\n Eigen::Vector3d aaxis_ba = so3::rot2vec(C_ab);\n\n // Get twist-translation vector using Jacobian\n Eigen::Vector3d rho_ba = so3::vec2jacinv(aaxis_ba)*r_ba_ina;\n\n // Return se3 algebra vector\n xi_ba << rho_ba, aaxis_ba;\n return xi_ba;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Compute the matrix log of a transformation matrix\n///\n/// Compute the inverse of the exponential map (the logarithmic map). This lets us go from\n/// a 4x4 transformation matrix back to a 6x1 se3 algebra vector (composed of a 3x1 axis-angle\n/// vector and 3x1 twist-translation vector). In some cases, when the rotation in the\n/// transformation matrix is 'numerically off', this involves some 'projection' back to SE(3).\n///\n/// xi_ba = ln(T_ab)\n///\n/// where xi_ba is the 6x1 se3 algebra vector. Alternatively, we that note that\n///\n/// xi_ab = -xi_ba = ln(T_ba) = ln(T_ab^{-1})\n///\n/// See Barfoot-TRO-2014 Appendix B2 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix tran2vec(const Eigen::Matrix4d& T_ab) {\n\n return tran2vec(T_ab.topLeftCorner<3,3>(), T_ab.topRightCorner<3,1>());\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 6x6 adjoint transformation matrix from the 3x3 rotation matrix and 3x1\n/// translation vector.\n///\n/// Builds the 6x6 adjoint transformation matrix from the 3x3 rotation matrix and 3x1\n/// translation vector.\n///\n/// Adjoint(T_ab) = Adjoint([C_ab r_ba_ina]) = [C_ab r_ba_ina^*C_ab] = exp(curlyhat(xi_ba))\n/// ([ 0^T 1]) [ 0 C_ab]\n///\n/// See eq. 101 in Barfoot-TRO-2014 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix tranAd(const Eigen::Matrix3d& C_ab,\n const Eigen::Vector3d& r_ba_ina) {\n\n Eigen::Matrix adjoint_T_ab = Eigen::Matrix::Zero();\n adjoint_T_ab.topLeftCorner<3,3>() = adjoint_T_ab.bottomRightCorner<3,3>() = C_ab;\n adjoint_T_ab.topRightCorner<3,3>() = so3::hat(r_ba_ina)*C_ab;\n return adjoint_T_ab;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 6x6 adjoint transformation matrix from a 4x4 one\n///\n/// Builds the 6x6 adjoint transformation matrix from a 4x4 transformation matrix\n///\n/// Adjoint(T_ab) = Adjoint([C_ab r_ba_ina]) = [C_ab r_ba_ina^*C_ab] = exp(curlyhat(xi_ba))\n/// ([ 0^T 1]) [ 0 C_ab]\n///\n/// See eq. 101 in Barfoot-TRO-2014 for more information.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix tranAd(const Eigen::Matrix4d& T_ab) {\n\n return tranAd(T_ab.topLeftCorner<3,3>(), T_ab.topRightCorner<3,1>());\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Construction of the 3x3 \"Q\" matrix, used in the 6x6 Jacobian of SE(3)\n///\n/// See eq. 102 in Barfoot-TRO-2014 for more information\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix3d vec2Q(const Eigen::Vector3d& rho_ba, const Eigen::Vector3d& aaxis_ba) {\n\n // Construct scalar terms\n const double ang = aaxis_ba.norm();\n const double ang2 = ang*ang;\n const double ang3 = ang2*ang;\n const double ang4 = ang3*ang;\n const double ang5 = ang4*ang;\n const double cang = cos(ang);\n const double sang = sin(ang);\n const double m2 = (ang - sang)/ang3;\n const double m3 = (1.0 - 0.5*ang2 - cang)/ang4;\n const double m4 = 0.5*(m3 - 3*(ang - sang - ang3/6)/ang5);\n\n // Construct matrix terms\n Eigen::Matrix3d rx = so3::hat(rho_ba);\n Eigen::Matrix3d px = so3::hat(aaxis_ba);\n Eigen::Matrix3d pxrx = px*rx;\n Eigen::Matrix3d rxpx = rx*px;\n Eigen::Matrix3d pxrxpx = pxrx*px;\n\n // Construct Q matrix\n return 0.5 * rx + m2 * (pxrx + rxpx + pxrxpx)\n - m3 * (px*pxrx + rxpx*px - 3*pxrxpx) - m4 * (pxrxpx*px + px*pxrxpx);\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Construction of the 3x3 \"Q\" matrix, used in the 6x6 Jacobian of SE(3)\n///\n/// See eq. 102 in Barfoot-TRO-2014 for more information\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix3d vec2Q(const Eigen::Matrix& xi_ba) {\n return vec2Q(xi_ba.head<3>(), xi_ba.tail<3>());\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 6x6 Jacobian matrix of SE(3) using the analytical expression\n///\n/// Build the 6x6 left Jacobian of SE(3).\n///\n/// For the sake of a notation, we assign subscripts consistence with the transformation,\n///\n/// J_ab = J(xi_ba)\n///\n/// Where applicable, we also note that\n///\n/// J(xi_ba) = Adjoint(exp(xi_ba^)) * J(-xi_ba),\n///\n/// and\n///\n/// Adjoint(exp(xi_ba^)) = identity + curlyhat(xi_ba) * J(xi_ba).\n///\n/// For more information see eq. 100 in Barfoot-TRO-2014.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix vec2jac(const Eigen::Vector3d& rho_ba,\n const Eigen::Vector3d& aaxis_ba) {\n\n // Init\n Eigen::Matrix J_ab = Eigen::Matrix::Zero();\n\n if(aaxis_ba.norm() < 1e-12) {\n\n // If angle is very small, so3 jacobian is Identity\n J_ab.topLeftCorner<3,3>() = J_ab.bottomRightCorner<3,3>() = Eigen::Matrix3d::Identity();\n J_ab.topRightCorner<3,3>() = 0.5*so3::hat(rho_ba);\n } else {\n\n // General analytical scenario\n J_ab.topLeftCorner<3,3>() = J_ab.bottomRightCorner<3,3>() = so3::vec2jac(aaxis_ba);\n J_ab.topRightCorner<3,3>() = se3::vec2Q(rho_ba, aaxis_ba);\n }\n return J_ab;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 6x6 Jacobian matrix of SE(3) from the se(3) algebra; note that the\n/// default parameter (numTerms = 0) will call the analytical solution, but the\n/// numerical solution can also be evaluating to some number of terms.\n///\n/// For more information see eq. 100 in Barfoot-TRO-2014.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix vec2jac(const Eigen::Matrix& xi_ba,\n unsigned int numTerms) {\n\n if (numTerms == 0) {\n\n // Analytical solution\n return vec2jac(xi_ba.head<3>(), xi_ba.tail<3>());\n } else {\n\n // Numerical solution (good for testing the analytical solution)\n Eigen::Matrix J_ab = Eigen::Matrix::Identity();\n\n // Incremental variables\n Eigen::Matrix x_small = se3::curlyhat(xi_ba);\n Eigen::Matrix x_small_n = Eigen::Matrix::Identity();\n\n // Loop over sum up to the specified numTerms\n for (unsigned int n = 1; n <= numTerms; n++) {\n x_small_n = x_small_n*x_small/double(n+1);\n J_ab += x_small_n;\n }\n return J_ab;\n }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 6x6 inverse Jacobian matrix of SE(3) using the analytical expression\n///\n/// Build the 6x6 inverse left Jacobian of SE(3).\n///\n/// For the sake of a notation, we assign subscripts consistence with the transformation,\n///\n/// J_ab_inverse = J(xi_ba)^{-1},\n///\n/// Please note that J_ab_inverse is not equivalent to J_ba:\n///\n/// J(xi_ba)^{-1} != J(-xi_ba)\n///\n/// For more information see eq. 103 in Barfoot-TRO-2014.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix vec2jacinv(const Eigen::Vector3d& rho_ba,\n const Eigen::Vector3d& aaxis_ba) {\n\n // Init\n Eigen::Matrix J66_ab_inv = Eigen::Matrix::Zero();\n\n if(aaxis_ba.norm() < 1e-12) {\n\n // If angle is very small, so3 jacobian is Identity\n J66_ab_inv.topLeftCorner<3,3>() = J66_ab_inv.bottomRightCorner<3,3>()\n = Eigen::Matrix3d::Identity();\n J66_ab_inv.topRightCorner<3,3>() = -0.5*so3::hat(rho_ba);\n } else {\n\n // General analytical scenario\n Eigen::Matrix3d J33_ab_inv = so3::vec2jacinv(aaxis_ba);\n J66_ab_inv.topLeftCorner<3,3>() = J66_ab_inv.bottomRightCorner<3,3>() = J33_ab_inv;\n J66_ab_inv.topRightCorner<3,3>() = -J33_ab_inv*se3::vec2Q(rho_ba, aaxis_ba)*J33_ab_inv;\n }\n return J66_ab_inv;\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Builds the 6x6 inverse Jacobian matrix of SE(3) from the se(3) algebra; note that\n/// the default parameter (numTerms = 0) will call the analytical solution, but the\n/// numerical solution can also be evaluating to some number of terms.\n///\n/// For more information see eq. 103 in Barfoot-TRO-2014.\n//////////////////////////////////////////////////////////////////////////////////////////////\nEigen::Matrix vec2jacinv(const Eigen::Matrix& xi_ba,\n unsigned int numTerms) {\n\n if (numTerms == 0) {\n\n // Analytical solution\n return vec2jacinv(xi_ba.head<3>(), xi_ba.tail<3>());\n } else {\n\n // Logic error\n if (numTerms > 20) {\n throw std::invalid_argument(\"Numerical vec2jacinv does not support numTerms > 20\");\n }\n\n // Numerical solution (good for testing the analytical solution)\n Eigen::Matrix J_ab = Eigen::Matrix::Identity();\n\n // Incremental variables\n Eigen::Matrix x_small = se3::curlyhat(xi_ba);\n Eigen::Matrix x_small_n = Eigen::Matrix::Identity();\n\n // Boost has a bernoulli package... but we shouldn't need more than 20\n Eigen::Matrix bernoulli;\n bernoulli << 1.0, -0.5, 1.0/6.0, 0.0, -1.0/30.0, 0.0, 1.0/42.0, 0.0, -1.0/30.0,\n 0.0, 5.0/66.0, 0.0, -691.0/2730.0, 0.0, 7.0/6.0, 0.0, -3617.0/510.0,\n 0.0, 43867.0/798.0, 0.0, -174611.0/330.0;\n\n // Loop over sum up to the specified numTerms\n for (unsigned int n = 1; n <= numTerms; n++) {\n x_small_n = x_small_n*x_small/double(n);\n J_ab += bernoulli(n)*x_small_n;\n }\n return J_ab;\n }\n}\n\n} // se3\n} // lgmath\n", "meta": {"hexsha": "430ecc9621b06718a8b1ff3284484d46ee8037f1", "size": 22227, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/se3/Operations.cpp", "max_stars_repo_name": "utiasASRL/lgmath", "max_stars_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T11:56:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:55:11.000Z", "max_issues_repo_path": "src/se3/Operations.cpp", "max_issues_repo_name": "utiasASRL/lgmath", "max_issues_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-06T21:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-08T15:23:38.000Z", "max_forks_repo_path": "src/se3/Operations.cpp", "max_forks_repo_name": "utiasASRL/lgmath", "max_forks_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-11-18T11:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-12T15:15:09.000Z", "avg_line_length": 41.2374768089, "max_line_length": 94, "alphanum_fraction": 0.5343051244, "num_tokens": 5836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.865224073888819, "lm_q1q2_score": 0.7976689676164449}} {"text": "// Boost.Geometry\n// QuickBook Example\n\n// Copyright (c) 2020, Aditya Mohan\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//[cross_product\n//` Calculate the cross product of two points\n\n\n#include \n#include \n#include \n\nnamespace bg = boost::geometry; /*< Convenient namespace alias >*/\n\nint main()\n{\n //Example 1 2D Vector\n \n bg::model::point p1(7.0, 2.0);\n bg::model::point p2(4.0, 5.0);\n \n bg::model::point r1;\n \n r1 = bg::cross_product(p1,p2);\n\n std::cout << \"Cross Product 1: \"<< r1.get<0>() << std::endl; //Note that the second point (r1.get<1>) would be undefined in this case\n \n //Example 2 - 3D Vector \n \n bg::model::point p3(4.0, 6.0, 5.0);\n bg::model::point p4(7.0, 2.0, 3.0);\n \n bg::model::point r2;\n \n r2 = bg::cross_product(p3,p4);\n\n std::cout << \"Cross Product 2: (\"<< r2.get<0>() <<\",\"<< r2.get<1>() <<\",\"<< r2.get<2>() << \")\"<< std::endl; \n \n return 0;\n}\n\n//]\n\n//[cross_product_output\n/*`\nOutput:\n[pre\nCross Product 1: 27\nCross Product 2: (8,23,-34)\n]\n*/\n//]\n", "meta": {"hexsha": "ca2906be120da7b8f052443f9dc63fe5328dfef8", "size": 1476, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/src/examples/arithmetic/cross_product.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "doc/src/examples/arithmetic/cross_product.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/geometry/doc/src/examples/arithmetic/cross_product.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 25.4482758621, "max_line_length": 139, "alphanum_fraction": 0.5982384824, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.8740772450055545, "lm_q1q2_score": 0.7975396791493381}} {"text": "// C++ includes\n#include \nusing namespace std;\n\n// Eigen includes\n#include \nusing namespace Eigen;\n\n// autodiff include\n#include \n#include \nusing namespace autodiff;\n\n// Define a 2nd order dual type using HigherOrderDual construct.\nusing dual2nd = HigherOrderDual<2>;\n\n// The scalar function for which the gradient is needed\ndual2nd f(const VectorXdual2nd& x, dual2nd p)\n{\n return x.cwiseProduct(x).sum() * exp(p); // sum([x(i) * x(i) for i = 1:5]) * exp(p)\n}\n\nint main()\n{\n VectorXdual2nd x(5); // the input vector x with 5 variables\n x << 1, 2, 3, 4, 5; // x = [1, 2, 3, 4, 5]\n\n dual2nd p = 3; // the input parameter vector p with 3 variables\n\n dual2nd u; // the output scalar u = f(x, p) evaluated together with gradient below\n VectorXd g; // gradient of f(x, p) evaluated together with Hessian below\n\n VectorXd H = hessian(f, wrtpack(p, x), at(x, p), u, g); // evaluate the function value u and its gradient vector gp = [du/dp, du/dx]\n\n cout << \"u = \" << u << endl; // print the evaluated output u\n cout << \"Hessian = \\n\" << H << endl; // print the evaluated gradient vector gp = [du/dp, du/dx]\n cout << \"g =\\n\" << g << endl; // print the evaluated gradient vector gp = [du/dp, du/dx]\n}\n", "meta": {"hexsha": "ecfc0a4075112aeb9fe1c7539614558aeff75889", "size": 1309, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/forward/example-forward-hessian-derivatives-using-eigen-with-scalar.cpp", "max_stars_repo_name": "rbharvs/autodiff", "max_stars_repo_head_hexsha": "d0305026b84c2f85f74012f312cc57bb1a894bd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-21T04:02:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T04:02:38.000Z", "max_issues_repo_path": "examples/forward/example-forward-hessian-derivatives-using-eigen-with-scalar.cpp", "max_issues_repo_name": "gayatri-a-b/autodiff", "max_issues_repo_head_hexsha": "98bdfea087cb67dd6e2a1a399e90bbd7ac4eb326", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-22T07:15:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-22T07:15:49.000Z", "max_forks_repo_path": "examples/forward/example-forward-hessian-derivatives-using-eigen-with-scalar.cpp", "max_forks_repo_name": "gayatri-a-b/autodiff", "max_forks_repo_head_hexsha": "98bdfea087cb67dd6e2a1a399e90bbd7ac4eb326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-02-26T13:14:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T03:52:45.000Z", "avg_line_length": 33.5641025641, "max_line_length": 137, "alphanum_fraction": 0.6447669977, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067260443809, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.7973064296883486}} {"text": "#include \n#include \nusing namespace std; \n\n#include \n#include \n\n#include \"sophus/so3.h\"\n#include \"sophus/se3.h\"\n\nint main( int argc, char** argv )\n{\n // 沿Z轴转90度的旋转矩阵\n Eigen::Matrix3d R = Eigen::AngleAxisd(M_PI/2, Eigen::Vector3d(0,0,1)).toRotationMatrix();\n \n Sophus::SO3 SO3_R(R); // Sophus::SO(3)可以直接从旋转矩阵构造\n Sophus::SO3 SO3_v( 0, 0, M_PI/2 ); // 亦可从旋转向量构造\n Eigen::Quaterniond q(R); // 或者四元数\n Sophus::SO3 SO3_q( q );\n // 上述表达方式都是等价的\n // 输出SO(3)时,以so(3)形式输出\n cout<<\"SO(3) from matrix: \"< Vector6d;\n Vector6d se3 = SE3_Rt.log();\n cout<<\"b属于se3([t', 旋转向量a]属于R6,是变换矩阵对应的李代数), b= \"<\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n/*\n\nhttps://en.wikipedia.org/wiki/Gauss%E2%80%93Newton_algorithm\nhttps://en.wikipedia.org/wiki/Non-linear_least_squares\nhttps://lingojam.com/SuperscriptGenerator\nhttps://lingojam.com/SubscriptGenerator\n\nconsider m data points:\n(x₁,y₁),(x₂,y₂),...(xₘ,yₘ)\n\nand a functions which has n parameters:\nβ=(β₁, β₂,..., βₙ)\n\nwhere m>=n\n\nthis gives us m residuals:\nrᵢ=yᵢ-f(xᵢ,β)\n\nour objective is minimize the:\n\nS=Σ(rᵢ)²\n\nThe minimum value of S occurs when the gradient is zero\n\nLets say we have the following dataset:\n\ni\t 1\t 2\t 3\t 4\t 5\t 6\t 7\nx\t 0.038\t0.194\t0.425\t0.626\t1.253\t2.500\t3.740\ny \t0.050\t0.127\t0.094\t0.2122\t0.2729\t0.2665\t0.3317\n\nand we have the folliwng function:\n\ny=(β₁*x)/(β₂+x)\n\nso our r is\nr₁=y₁ - (β₁*x₁)/(β₂+x₁)\nr₂=y₂ - (β₁*x₂)/(β₂+x₂)\nr₃=y₃ - (β₁*x₃)/(β₂+x₃)\nr₄=y₄ - (β₁*x₄)/(β₂+x₄)\nr₅=y₅ - (β₁*x₅)/(β₂+x₅)\nr₆=y₆ - (β₁*x₆)/(β₂+x₆)\nr₇=y₇ - (β₁*x₇)/(β₂+x₇)\n\nr(β)₂ₓ₇ -> J₇ₓ₂\n\n\nσrᵢ/σβ₁=-xᵢ/(β₂+xᵢ)\n\nσrᵢ/σβ₂=(β₁*xᵢ)/(β₂xᵢ)²\n\n\nβᵏ⁺¹=βᵏ- (JᵀJ)⁻¹Jᵀr(βᵏ)\n*/\n\n\n\n// Generic functor\ntemplate\nstruct Functor\n{\n // Information that tells the caller the numeric type (eg. double) and size (input / output dim)\n typedef _Scalar Scalar;\n enum {\n InputsAtCompileTime = NX,\n ValuesAtCompileTime = NY\n};\n// Tell the caller the matrix sizes associated with the input, output, and jacobian\ntypedef Eigen::Matrix InputType;\ntypedef Eigen::Matrix ValueType;\ntypedef Eigen::Matrix JacobianType;\n\n// Local copy of the number of inputs\nint m_inputs, m_values;\n\n// Two constructors:\nFunctor() : m_inputs(InputsAtCompileTime), m_values(ValuesAtCompileTime) {}\nFunctor(int inputs, int values) : m_inputs(inputs), m_values(values) {}\n\n// Get methods for users to determine function input and output dimensions\nint inputs() const { return m_inputs; }\nint values() const { return m_values; }\n\n};\n\ntypedef std::vector > Point2DVector;\n\n//Point2DVector GeneratePoints(const unsigned int numberOfPoints)\n\nstruct SubstrateConcentrationFunctor : Functor\n{\n\n SubstrateConcentrationFunctor(Eigen::MatrixXd points): Functor(points.cols(),points.rows())\n {\n this->Points = points;\n }\n\n int operator()(const Eigen::VectorXd &z, Eigen::VectorXd &r) const\n {\n double x_i,y_i,beta1,beta2;\n for(unsigned int i = 0; i < this->Points.rows(); ++i)\n {\n y_i=this->Points.row(i)(1);\n x_i=this->Points.row(i)(0);\n beta1=z(0);\n beta2=z(1);\n r(i) =y_i-(beta1*x_i) /(beta2+x_i);\n }\n\n return 0;\n }\n Eigen::MatrixXd Points;\n\n int inputs() const { return 2; } // There are two parameters of the model, beta1, beta2\n int values() const { return this->Points.rows(); } // The number of observations\n};\n\n\n\nvoid SubstrateConcentrationLeastSquare()\n{\n/*\nour data:\n\nx y\n0.038,0.050;\n0.194,0.127;\n0.425,0.094;\n0.626,0.2122;\n1.253,0.2729;\n2.500,0.2665;\n3.740,0.3317;\n\nthe last column in the matrix should be \"y\"\n\n*/\n\n\n Eigen::MatrixXd points(7,2);\n\n\n points.row(0)<< 0.038,0.050;\n points.row(1)<<0.194,0.127;\n points.row(2)<<0.425,0.094;\n points.row(3)<<0.626,0.2122;\n points.row(4)<<1.253,0.2729;\n points.row(5)<<2.500,0.2665;\n points.row(6)<<3.740,0.3317;\n\n SubstrateConcentrationFunctor functor(points);\n Eigen::NumericalDiff numDiff(functor);\n\n std::cout<<\"functor.Points.size(): \" <\n#include \n#include \n\ntemplate\nT MultiVarFunction(const T &x,const T& y)\n{\n T z=x*cos(y);\n return z;\n}\n\nvoid MultiVarFunctionDerivativesExample()\n{\n Eigen::AutoDiffScalar x,y,z_derivative;\n\n x.value()=2 ;\n y.value()=M_PI/4;\n\n/*\n Eigen::VectorXd::Unit(2, 0) means a unit vector with first element be 1\n\n 0\n 1\n\n which means we want compute the derivates relative to the first element\n*/\n //we telling we want dz/dx\n x.derivatives() = Eigen::VectorXd::Unit(2, 0);\n\n //we telling we want dz/dy\n y.derivatives() = Eigen::VectorXd::Unit(2, 1);\n\n z_derivative = MultiVarFunction(x, y);\n\n std::cout << \"AutoDiff:\" << std::endl;\n std::cout << \"Function output: \" << z_derivative.value() << std::endl;\n std::cout << \"Derivative: \\n\" << z_derivative.derivatives()<< std::endl;\n\n}\n\ntemplate\nstruct VectorFunction {\n\n typedef _Scalar Scalar;\n\n enum\n {\n InputsAtCompileTime = NX,\n ValuesAtCompileTime = NY\n };\n\n // Also needed by Eigen\n typedef Eigen::Matrix InputType;\n typedef Eigen::Matrix ValueType;\n\n // Vector function\n template \n void operator()(const Eigen::Matrix& x, Eigen::Matrix* y ) const\n {\n (*y)(0,0) = 10.0*pow(x(0,0)+3.0,2) +pow(x(1,0)-5.0,2) ;\n (*y)(1,0) = (x(0,0)+1)*x(1,0);\n (*y)(2,0) = sin(x(0,0))*x(1,0);\n }\n};\n\n\n\nvoid JacobianDerivativesExample()\n{\n\n Eigen::Matrix x;\n Eigen::Matrix y;\n Eigen::Matrix fjac;\n\n Eigen::AutoDiffJacobian< VectorFunction > JacobianDerivatives;\n\n // Set values in x, y and fjac...\n\n\n x(0,0)=2.0;\n x(1,0)=3.0;\n\n JacobianDerivatives(x, &y, &fjac);\n\n std::cout << \"jacobian of matrix at \"<< x(0,0)<<\",\"<\n#include \n#include \n#include \n#include \"sophus/se3.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\n\nint main(int argc, char **argv) {\n // Rotation matrix with 90 degrees along Z axis\n Matrix3d R = AngleAxisd(M_PI / 2, Vector3d(0, 0, 1)).toRotationMatrix();\n\n // or quaternion\n Quaterniond q(R);\n \n // Sophus::SO3d can be constructed from rotation matrix\n Sophus::SO3d SO3_R(R);\n\n // or a from a quaternion\n Sophus::SO3d SO3_q(q);\n\n // They are equivalent\n cout << \" SO(3) from matrix:\\n\" << SO3_R.matrix() << \"\\n\";\n cout << \" SO(3) from quaternion:\\n\" << SO3_q.matrix() << \"\\n\";\n cout << \"They are equal!\" << \"\\n***************\\n\";\n\n // Use logarithic map to get the Lie Algebra\n Vector3d so3 = SO3_R.log();\n cout << \"so3 = \\n\" << so3.transpose() << \"\\n\\n\";\n // hat is from vector to skew-symmetric matrix\n cout << \"so3 hat=\\n\" << Sophus::SO3d::hat(so3) << \"\\n\";\n // inversely from matrix to vector\n cout << \"so3 hat vee=\" << Sophus::SO3d::vee(Sophus::SO3d::hat(so3)).transpose() << \"\\n\";\n\n // update by perturbation model\n // this is a small update\n Vector3d update_so3(1e-4, 0, 0);\n Sophus::SO3d SO3_updated = Sophus::SO3d::exp(update_so3) * SO3_R;\n cout << \"SO3 updated = \\n\" << SO3_updated.matrix() << \"\\n\";\n cout << \"*********************\\n\";\n\n\n // Similar for SE(3)\n // translation 1 along X\n Vector3d t(1, 0, 0);\n // construct SE3 from R, t\n Sophus::SE3d SE3_Rt(R, t); \n // or SE3 from q, t\n Sophus::SE3d SE3_qt(q, t);\n cout << \"SE3 from R, t= \\n\" << SE3_Rt.matrix() << \"\\n\";\n cout << \"SE3 from q, t= \\n\" << SE3_qt.matrix() << \"\\n\";\n \n // Lie Algebra is a 6d vector - we provide a typedef \n typedef Eigen::Matrix Vector6d;\n Vector6d se3 = SE3_Rt.log();\n cout << \"se3 = \" << se3.transpose() << \"\\n\";\n\n return 0;\n}\n\n", "meta": {"hexsha": "df919145393414421ea833e8eecd2386bab94226", "size": 1833, "ext": "cc", "lang": "C++", "max_stars_repo_path": "ch3/use_sophus.cc", "max_stars_repo_name": "prasannavk/slam_experiments", "max_stars_repo_head_hexsha": "5890eabfececbffba01b0f5ae40e99ca53f6c25c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch3/use_sophus.cc", "max_issues_repo_name": "prasannavk/slam_experiments", "max_issues_repo_head_hexsha": "5890eabfececbffba01b0f5ae40e99ca53f6c25c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch3/use_sophus.cc", "max_forks_repo_name": "prasannavk/slam_experiments", "max_forks_repo_head_hexsha": "5890eabfececbffba01b0f5ae40e99ca53f6c25c", "max_forks_repo_licenses": ["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.564516129, "max_line_length": 90, "alphanum_fraction": 0.5990180033, "num_tokens": 639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8807970732843033, "lm_q1q2_score": 0.7956188889934042}} {"text": "#include \"catmull_rom_interpolation.h\"\n#include \n#include\n\nEigen::Vector3d catmull_rom_interpolation(\n const std::vector > & keyframes,\n double t)\n{\n /////////////////////////////////////////////////////////////////////////////\n /**\n * The solution below is based on the textbook pg. 383.\n */\n // Check if there are keyframes\n if (keyframes.size() == 0) {\n return Eigen::Vector3d(0, 0, 0);\n }\n\n // Loop the query times if t is greater than the largest keyframe time\n t = std::fmod(t, keyframes.back().first);\n\n // Step 1: Find index i for query time t. This is curve segment i\n int i = 0;\n for (i = 0; i < keyframes.size() - 1; i++) {\n // find t_i < t <= t_i+1\n if (keyframes[i].first < t && t <= keyframes[i+1].first) {\n break;\n }\n }\n\n // Set up some variables\n Eigen::Vector3d p0, p1, p2, p3; // points\n double t0, t1, t2, t3; // times\n double tension = 0.0;\n\n /**\n * Since Catmull-Rom doesn't interpolate the first or last point, we will use\n * cosine interpolation for these two points.\n */\n\n // Case 1: first point or last point\n if (i == 0 || i == keyframes.size() - 2) {\n // Source: http://paulbourke.net/miscellaneous/interpolation/\n p0 = keyframes[i].second;\n p1 = keyframes[i+1].second;\n\n t0 = keyframes[i].first;\n t1 = keyframes[i+1].first;\n\n double u = (t - t0) / (t1 - t0);\n double mu2 = (1 - cos(u * M_PI)) / 2;\n\n // Interpolate\n return (1 - mu2) * p0 + mu2 * p1;\n }\n\n // Case 2: some middle point\n /**\n * Find our four points. We will interpolate between p1 and p2.\n * We want:\n * f(0) = p1\n * f(1) = p2\n * f'(0) = (p2 - p0) / (t2 - t0)\n * f'(1) = (p3 - p1) / (t3 - t1)\n */\n p0 = keyframes[i-1].second;\n p1 = keyframes[i].second;\n p2 = keyframes[i+1].second;\n p3 = keyframes[i+2].second;\n\n t0 = keyframes[i-1].first;\n t1 = keyframes[i].first;\n t2 = keyframes[i+1].first;\n t3 = keyframes[i+2].first;\n\n // Calculate u --- unit parameter in [0, 1]\n double _u = (t - t1) / (t2 - t1);\n Eigen::RowVector4d u = Eigen::RowVector4d(1, _u, pow(_u, 2), pow(_u, 3));\n\n // Calculate derivatives/tangents at P1 and P2\n // Source: https://en.wikipedia.org/wiki/Cubic_Hermite_spline#Catmull%E2%80%93Rom_spline\n Eigen::Vector3d v1 = (p2 - p0) / (t2 - t0);\n Eigen::Vector3d v2 = (p3 - p1) / (t3 - t1);\n\n // Calculate constraint matrix. See iPad for calculations\n Eigen::Matrix4d C;\n C <<\n 1, 1 - (t2 - t0), 1, 1,\n 1, 0, 0, 0,\n 1, 1, 1, 1,\n 1, (t3 - t1), 2 * (t3 - t1), 3 * (t3 - t1);\n\n // Calculate the cardinal matrix B and blending functions b(u)\n Eigen::Matrix4d B = C.inverse();\n // Eigen::Vector4d b_of_u = (u * B);\n\n // Create a matrix for the control points\n Eigen::Matrix p;\n p.row(0) = p0;\n p.row(1) = p1;\n p.row(2) = p2;\n p.row(3) = p3;\n\n\n // Interpolate\n return u * B * p;\n /////////////////////////////////////////////////////////////////////////////\n}\n\n\n\n\n\n\n\n/**\n * This solution below is based on the wikipedia page:\n * https://en.wikipedia.org/wiki/Cubic_Hermite_spline#Catmull%E2%80%93Rom_spline\n * This solution also works and should be doing the exact same thing as above.\n * It's probably a bit faster as well, but the solution above is more general.\n */\n// #include \"catmull_rom_interpolation.h\"\n// #include \n// #include\n\n// Eigen::Vector3d catmull_rom_interpolation(\n// const std::vector > & keyframes,\n// double t)\n// {\n// /////////////////////////////////////////////////////////////////////////////\n// // Check if there are keyframes\n// if (keyframes.size() == 0) {\n// return Eigen::Vector3d(0, 0, 0);\n// }\n\n// // Loop the query times if t is greater than the largest keyframe time\n// t = std::fmod(t, keyframes.back().first);\n\n// // Step 1: Find index i for query time t. This is curve segment i\n// int i = 0;\n// for (i = 0; i < keyframes.size() - 1; i++) {\n// // find t_i < t <= t_i+1\n// if (keyframes[i].first < t && t <= keyframes[i+1].first) {\n// break;\n// }\n// }\n\n// // Set up some variables\n// Eigen::Vector3d p0, p1, p2, p3; // points\n// double t0, t1, t2, t3; // times\n// double tension = 0.0;\n\n// /**\n// * Since Catmull-Rom doesn't interpolate the first or last point, we will use\n// * cosine interpolation for these two points.\n// */\n\n// // Case 1: first point or last point\n// if (i == 0 || i == keyframes.size() - 2) {\n// // Source: http://paulbourke.net/miscellaneous/interpolation/\n// p0 = keyframes[i].second;\n// p1 = keyframes[i+1].second;\n\n// t0 = keyframes[i].first;\n// t1 = keyframes[i+1].first;\n\n// double u = (t - t0) / (t1 - t0);\n// double mu2 = (1 - cos(u * M_PI)) / 2;\n\n// // Interpolate\n// return (1 - mu2) * p0 + mu2 * p1;\n// }\n\n// // Case 2: some middle point\n// /**\n// * Find our four points. We will interpolate between p1 and p2.\n// * We want:\n// * f(0) = p1\n// * f(1) = p2\n// * f'(0) = (p2 - p0) / (t2 - t0)\n// * f'(1) = (p3 - p1) / (t3 - t1)\n// */\n// p0 = keyframes[i-1].second;\n// p1 = keyframes[i].second;\n// p2 = keyframes[i+1].second;\n// p3 = keyframes[i+2].second;\n\n// t0 = keyframes[i-1].first;\n// t1 = keyframes[i].first;\n// t2 = keyframes[i+1].first;\n// t3 = keyframes[i+2].first;\n\n// // Calculate u --- unit parameter in [0, 1]\n// double u = (t - t1) / (t2 - t1);\n\n// // Calculate derivatives/tangents at P1 and P2\n// // Source: https://en.wikipedia.org/wiki/Cubic_Hermite_spline#Catmull%E2%80%93Rom_spline\n// Eigen::Vector3d m1 = (p2 - p0) / (t2 - t0);\n// Eigen::Vector3d m2 = (p3 - p1) / (t3 - t1);\n\n// // Set up our blending functions\n// double h_00 = 2 * pow(u, 3) - 3 * pow(u, 2) + 1;\n// double h_10 = pow(u, 3) - 2 * pow(u, 2) + u;\n// double h_01 = -2 * pow(u, 3) + 3 * pow(u, 2);\n// double h_11 = pow(u, 3) - pow(u, 2);\n\n// Eigen::Vector3d interp = h_00 * p1 + h_10 * m1 + h_01 * p2 + h_11 * m2;\n\n\n// return interp;\n// /////////////////////////////////////////////////////////////////////////////\n// }\n", "meta": {"hexsha": "dc2c6e2b566204957da474d2ff9b5ce265aa86bd", "size": 6229, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/catmull_rom_interpolation.cpp", "max_stars_repo_name": "ericpko/computer-graphics-kinematics", "max_stars_repo_head_hexsha": "6fb0fe8443289781964a3246e11e01e394143d02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/catmull_rom_interpolation.cpp", "max_issues_repo_name": "ericpko/computer-graphics-kinematics", "max_issues_repo_head_hexsha": "6fb0fe8443289781964a3246e11e01e394143d02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/catmull_rom_interpolation.cpp", "max_forks_repo_name": "ericpko/computer-graphics-kinematics", "max_forks_repo_head_hexsha": "6fb0fe8443289781964a3246e11e01e394143d02", "max_forks_repo_licenses": ["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.3820754717, "max_line_length": 93, "alphanum_fraction": 0.5342751646, "num_tokens": 2146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938414, "lm_q2_score": 0.8807970670261976, "lm_q1q2_score": 0.7956188810474744}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"psm.h\"\n\nusing namespace std;\nusing namespace std::chrono;\nusing namespace boost::multiprecision;\n\ntypedef number, et_off> cpp_bin_float_half;\ntypedef number, et_off> cpp_bin_float_bfloat;\n\nofstream out;\n\ntemplate \nT absval(T v) {\n return (v < T(0)) ? -v : v;\n}\n\ntemplate \nT nthCoefficientProduct(vector &x, vector &y, int n){\n /* This method computes the nth coefficient of x*y, runs in O(n)\n */\n T sum = 0;\n for(int i = 0; i<=n; i++){\n sum+=x[i]*y[n-i];\n }\n return sum;\n}\n\ntemplate \nvoid updateNthCoefficient(vector &x, vector &xx, vector &xxx, int n){\n /* This method asumes we have the n-th coefficient for x, it then updates the rest\n *\n * This method runs in O(N)\n */\n xx[n] = nthCoefficientProduct(x,x,n);\n xxx[n] = nthCoefficientProduct(xx,x,n);\n }\n\ntemplate \nvector coefficients(T x0, int nn){\n /* Inputs\n * n : order of the polynomial approximation\n * x0: initial conditions\n * Output:\n * coefficients of the nth polynomial approximation in increasing order\n *\n * Runs in O(n^2), memory O(n)\n */\n vector x(nn,0);\n vector xx(nn,0);\n vector xxx(nn,0);\n vector xprime(nn,0);\n x[0] = x0; //The initial condition is x0\n updateNthCoefficient(x,xx,xxx,0);\n\n for(int n = 0; n(x,xx,xxx,n+1);\n }\n return x;\n}\n\ntemplate\npair computeNext(T x0, T step, bool forward, int n){\n /*Inputs:\n * x0 : parameters of the ODE\n * step: Size of the step\n * forward: if you want to go forward or backwards\n * Outputs:\n * x(t) where t = x0+step and x solves the equation x' = x^2-x^3\n */\n vector coeff = coefficients(x0,n);\n vector deriv = derivative(coeff);\n if(forward){\n return make_pair(eval(coeff,step), eval(deriv,step));\n }\n else{\n return make_pair(eval(coeff,-step), eval(deriv,-step));\n }\n}\n\ntemplate\npair, vector > generateSolutionStepper(T x0, T step, bool forward, T end, int n){\n /*Inputs:\n * x0 : parameters of the ODE\n * step: Size of the step\n * end : End point to solve the solution (solves in [0,end])\n * n : Degree of the approximation\n * forward: if you want to go forward or backwards\n * Output:\n * vector of solutions to the equation x' = x^2-x^3\n */\n step = absval(step);\n vector sol;\n sol.push_back(x0);\n vector deriv;\n T xx = x0 * x0;\n deriv.push_back(xx-x0*xx);\n T newx0 = x0;\n for(int k = 1; step*k<=end; k++){\n //cout << \"step \" << k << endl;\n pair cond = computeNext(newx0,step,forward,n);\n sol.push_back(cond.first);\n deriv.push_back(cond.second);\n newx0 = cond.first;\n }\n return make_pair(sol,deriv);\n}\n\ntemplate\nvoid solve_p4(T x0, T end, T step, int n, string fn)\n{\n // generate solutions\n //cout << \"size = \" << sizeof(x0) << endl;\n vector coeff = coefficients(x0,n);\n auto stepperB = generateSolutionStepper(x0, step, 0, end, n);\n vector solutionStepperB = stepperB.first;\n vector derivSolutionB = stepperB.second;\n auto stepperF = generateSolutionStepper(x0, step, 1, end, n);\n vector solutionStepperF = stepperF.first;\n vector derivSolutionF = stepperF.second;\n\n // print backward solution\n out.open(fn);\n for(int i = solutionStepperB.size()-1; i>=0; i--) {\n int dig = 1000;\n out.precision(5);\n out << fixed << setw(15) << -i*step << \" \";\n T stepper = solutionStepperB[i];\n T deriv = derivSolutionB[i];\n if (absval(stepper) > dig || absval(deriv) > dig) {\n out << scientific << setw(15) << stepper << \" \" << setw(15) << deriv << \"\\n\";\n }\n else{\n out << fixed << setw(15) << stepper << \" \" << setw(15) << deriv << \"\\n\";\n }\n }\n\n // print forward solution\n for(int i = 1; i dig || absval(deriv) > dig) {\n out << scientific << setw(15) << stepper << \" \" << setw(15) << deriv << \"\\n\";\n }\n else{\n out << fixed << setw(15) << stepper << \" \" << setw(15) << deriv << \"\\n\";\n }\n }\n out.close();\n}\n\nint main(int argc, const char* argv[])\n{\n // check parameters\n if (argc != 5) {\n cout << \"Usage: \" << argv[0] << \"
\" << endl;\n return EXIT_FAILURE;\n }\n\n // parse parameters\n double x0 = stod(argv[1], NULL);\n double end = stod(argv[2], NULL);\n double step = stod(argv[3], NULL);\n string rtype = string(argv[4]);\n\n if (rtype == \"float\") {\n solve_p4((float)x0, (float)end, (float)step, 10, \"out.dat\");\n } else if (rtype == \"quad\") {\n solve_p4(cpp_bin_float_quad(x0), cpp_bin_float_quad(end), cpp_bin_float_quad(step), 10, \"out.dat\");\n } else if (rtype == \"half\") {\n solve_p4(cpp_bin_float_half(x0), cpp_bin_float_half(end), cpp_bin_float_half(step), 10, \"out.dat\");\n } else if (rtype == \"bfloat\") {\n solve_p4(cpp_bin_float_bfloat(x0), cpp_bin_float_bfloat(end), cpp_bin_float_bfloat(step), 10, \"out.dat\");\n } else if (rtype == \"rational\") {\n solve_p4(cpp_rational(x0), cpp_rational(end), cpp_rational(step), 10, \"out.dat\");\n } else {\n solve_p4(x0, end, step, 10, \"out.dat\");\n }\n\n return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "051a52972caa2d9b1afedd4db832007ff0795e05", "size": 6149, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "solve_p4.cpp", "max_stars_repo_name": "lam2mo/jmu-reu-ode", "max_stars_repo_head_hexsha": "2b60b869d2050a986cb42391d33af6c647e0a4c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-09T16:48:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T17:12:01.000Z", "max_issues_repo_path": "solve_p4.cpp", "max_issues_repo_name": "lam2mo/jmu-reu-ode", "max_issues_repo_head_hexsha": "2b60b869d2050a986cb42391d33af6c647e0a4c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solve_p4.cpp", "max_forks_repo_name": "lam2mo/jmu-reu-ode", "max_forks_repo_head_hexsha": "2b60b869d2050a986cb42391d33af6c647e0a4c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-11T15:51:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-11T15:51:05.000Z", "avg_line_length": 30.8994974874, "max_line_length": 128, "alphanum_fraction": 0.5865994471, "num_tokens": 1822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.874077222043951, "lm_q1q2_score": 0.7953289924269512}} {"text": "#ifndef ALM_HERMITE_QUATERNION_CURVE_H\n#define ALM_HERMITE_QUATERNION_CURVE_H\n\n#include \n#include \n#include \n#include \n\n// Hermite Quaternion curve for global frame quaternion trajectory given boundary conditions\n// also computes global frame angular velocity and angular acceleration for s \\in [0,1]\n\nclass HermiteQuaternionCurve{\npublic:\n HermiteQuaternionCurve();\n HermiteQuaternionCurve(const Eigen::Quaterniond & quat_start, const Eigen::Vector3d & angular_velocity_start,\n const Eigen::Quaterniond & quat_end, const Eigen::Vector3d & angular_velocity_end);\n ~HermiteQuaternionCurve();\n\n void initialize(const Eigen::Quaterniond & quat_start, const Eigen::Vector3d & angular_velocity_start,\n const Eigen::Quaterniond & quat_end, const Eigen::Vector3d & angular_velocity_end);\n\n // All values are expressed in \"world frame\"\n void evaluate(const double & s_in, Eigen::Quaterniond & quat_out);\n void getAngularVelocity(const double & s_in, Eigen::Vector3d & ang_vel_out);\n void getAngularAcceleration(const double & s_in, Eigen::Vector3d & ang_acc_out);\n\nprivate:\n Eigen::Quaterniond qa; // Starting quaternion\n Eigen::Vector3d omega_a; // Starting Angular Velocity\n Eigen::Quaterniond qb; // Ending quaternion\n Eigen::Vector3d omega_b; // Ending Angular velocity\n\n Eigen::AngleAxisd omega_a_aa; // axis angle representation of omega_a\n Eigen::AngleAxisd omega_b_aa; // axis angle representation of omega_b\n\n void initialize_data_structures();\n\n void computeBasis(const double & s_in); // computes the basis functions\n void computeOmegas();\n\n Eigen::Quaterniond q0; // quat0\n Eigen::Quaterniond q1; // quat1\n Eigen::Quaterniond q2; // quat1\n Eigen::Quaterniond q3; // quat1\n\n double b1; // basis 1\n double b2; // basis 2\n double b3; // basis 3\n\n double bdot1; // 1st derivative of basis 1\n double bdot2; // 1st derivative of basis 2\n double bdot3; // 1st derivative of basis 3\n\n double bddot1; // 2nd derivative of basis 1\n double bddot2; // 2nd derivative of basis 2\n double bddot3; // 2nd derivative of basis 3\n\n Eigen::Vector3d omega_1;\n Eigen::Vector3d omega_2;\n Eigen::Vector3d omega_3;\n\n Eigen::AngleAxisd omega_1aa;\n Eigen::AngleAxisd omega_2aa;\n Eigen::AngleAxisd omega_3aa;\n\n // Allocate memory for quaternion operations\n Eigen::Quaterniond qtmp1;\n Eigen::Quaterniond qtmp2;\n Eigen::Quaterniond qtmp3;\n\n // progression variable\n double s_;\n // by default clamps within 0 and 1.\n double clamp(const double & s_in, double lo = 0.0, double hi = 1.0);\n\n void printQuat(const Eigen::Quaterniond & quat);\n\n};\n\n#endif", "meta": {"hexsha": "593041a4127ebafe4660f9b501966b35eb107b02", "size": 2649, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Utils/Math/hermite_quaternion_curve.hpp", "max_stars_repo_name": "BharathMasetty/PnC", "max_stars_repo_head_hexsha": "3800bd7e3c5dd5ffa00e6a5f09d48d21c405206f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-04T22:36:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-04T22:36:54.000Z", "max_issues_repo_path": "Utils/Math/hermite_quaternion_curve.hpp", "max_issues_repo_name": "BharathMasetty/PnC", "max_issues_repo_head_hexsha": "3800bd7e3c5dd5ffa00e6a5f09d48d21c405206f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Utils/Math/hermite_quaternion_curve.hpp", "max_forks_repo_name": "BharathMasetty/PnC", "max_forks_repo_head_hexsha": "3800bd7e3c5dd5ffa00e6a5f09d48d21c405206f", "max_forks_repo_licenses": ["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.1125, "max_line_length": 111, "alphanum_fraction": 0.7395243488, "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632288833652, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7952660573061722}} {"text": "#include \"plugins/evaluate/convexhull.h\"\n#include \n\n// Implementation of Andrew's monotone chain 2D convex hull algorithm.\n// Asymptotic complexity: O(n log n).\n// Practical performance: 0.5-1.0 seconds for n=1000000 on a 1GHz machine.\n#include \n#include \n\n// 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product.\n// Returns a positive value, if OAB makes a counter-clockwise turn,\n// negative for clockwise turn, and zero if the points are collinear.\nfloat cross(const Eigen::Vector2f O, const Eigen::Vector2f A, const Eigen::Vector2f B) {\n return (long)(A.x() - O.x()) * (B.y() - O.y()) - (long)(A.y() - O.y()) * (B.x() - O.x());\n}\n\n// Returns a list of points on the convex hull in counter-clockwise order.\n// Note: the last point in the returned list is the same as the first one.\nstd::vector convex_hull(std::vector idxs, std::function & getPoint){\n int n = idxs.size(), k = 0;\n std::vector hull(2*n);\n\n // Sort points lexicographically\n sort(idxs.begin(), idxs.end(), [&getPoint](int a_, int b_){\n Eigen::Vector2f a = getPoint(a_);\n Eigen::Vector2f b = getPoint(b_);\n return a.x() < b.x() || (a.x() == b.x() && a.y() < b.y());\n });\n\n // Build lower hull\n for (int i = 0; i < n; ++i) {\n while (k >= 2 && cross(getPoint(hull[k-2]), getPoint(hull[k-1]), getPoint(idxs[i])) <= 0) k--;\n hull[k++] = idxs[i];\n }\n\n // Build upper hull\n for (int i = n-2, t = k+1; i >= 0; i--) {\n while (k >= t && cross(getPoint(hull[k-2]), getPoint(hull[k-1]), getPoint(idxs[i])) <= 0) k--;\n hull[k++] = idxs[i];\n }\n\n hull.resize(k);\n return hull;\n}\n", "meta": {"hexsha": "c08e7f564a0493ea2b487c2fdce96aa2b96e719d", "size": 1720, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/plugins/evaluate/convexhull.cpp", "max_stars_repo_name": "circlingthesun/cloudclean", "max_stars_repo_head_hexsha": "4b9496bc3b52143c35f0ad83ee68bbc5e8aa32d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-10-18T16:10:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-28T01:52:24.000Z", "max_issues_repo_path": "src/plugins/evaluate/convexhull.cpp", "max_issues_repo_name": "circlingthesun/cloudclean", "max_issues_repo_head_hexsha": "4b9496bc3b52143c35f0ad83ee68bbc5e8aa32d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/plugins/evaluate/convexhull.cpp", "max_forks_repo_name": "circlingthesun/cloudclean", "max_forks_repo_head_hexsha": "4b9496bc3b52143c35f0ad83ee68bbc5e8aa32d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-12-13T07:39:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-29T13:13:48.000Z", "avg_line_length": 38.2222222222, "max_line_length": 102, "alphanum_fraction": 0.6034883721, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.86153820232079, "lm_q1q2_score": 0.79523350228613}} {"text": "\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"readfile.h\"\n\nusing namespace Eigen;\n\n\nVectorXd stochasticGD(const MatrixXd& X, const VectorXd& Y)\n{\n const size_t allRows = X.rows();\n VectorXd theta = VectorXd::Zero(X.cols());\n\n for (size_t i = 0; i < allRows; ++i) {\n VectorXd hTheta = X.row(i) * theta;\n VectorXd diff = hTheta - Y.row(i);\n\n for (size_t j = 0; j < theta.rows(); ++j) {\n theta.row(j) -= (diff * X.row(i).col(j));\n }\n }\n\n return theta;\n}\n\ntemplate \nVectorXd batchGD(const MatrixXd& X, const VectorXd& Y, OutputIterator costs, const size_t maxIter = 1000)\n{\n const size_t allRows = X.rows();\n VectorXd theta = VectorXd::Zero(X.cols());\n\n const double acceptableCost = 0.000001;\n double cost = std::numeric_limits::infinity();\n for (size_t i = 0; i < maxIter && cost > acceptableCost; ++i) {\n VectorXd hTheta = X * theta;\n VectorXd diff = hTheta - Y;\n\n auto diff_T = diff.transpose();\n\n for (size_t j = 0; j < theta.rows(); ++j) {\n theta.row(j) -= (diff_T * X.col(j)) / allRows;\n }\n\n costs = cost = (diff_T * diff / (2 * allRows))(0);\n }\n\n return theta;\n}\n\nvoid plotVector(const std::vector& vec)\n{\n FILE* gp = popen(\"gnuplot\", \"w\");\n fprintf(gp, \"reset \\n\");\n // fprintf(gp, \"set terminal qt \\n\");\n fprintf(gp, \"set grid \\n\");\n fprintf(gp, \"set title 'Cost Function' \\n\");\n fprintf(gp, \"set xlabel 'Number of Iterations' \\n\");\n fprintf(gp, \"set ylabel 'Cost J' \\n\");\n fprintf(gp, \"set style data lines \\n\");\n fprintf(gp, \"plot '-' lw 1 \\n\");\n\n size_t i = 0;\n for (const auto& val : vec) {\n fprintf(gp, \"%zu %f \\n\", i++, val);\n }\n fprintf(gp, \"e\\n\");\n\n fflush(gp);\n\n puts(\"Hit enter to continue\");\n getchar();\n pclose(gp);\n}\n\nint main(int argc, char* argv[])\n{\n constexpr int rows = 13;\n constexpr int columns = 3;\n MatrixXd data(rows, columns);\n\n if (argc < 2) {\n printf(\"usage: %s \\n\", argv[0]);\n return 0;\n }\n\n if (readData(argv[1], data) < 0) {\n fprintf(stderr, \"Error reading data\\n\");\n return 0;\n }\n\n data.conservativeResize(NoChange, data.cols() + 1);\n data.col(columns) = data.col(columns - 1); \n data.col(columns - 1).setOnes(); // Set intercept to column to 1\n\n std::vector costs;\n VectorXd theta = batchGD(data.block(0, 0), data.col(columns), std::back_inserter(costs));\n std::cout << \"theta: \" << theta.transpose() << std::endl;\n std::cout << \"iterations: \" << costs.size() << std::endl;\n\n plotVector(costs);\n\n // std::cout << \"Answer ->\\n\" << (X.transpose() * X).ldlt().solve(X.transpose() * Y) << std::endl;\n // std::cout << \"Answer ->\\n\" << X.completeOrthogonalDecomposition().solve(Y) << std::endl;\n\n return 0;\n}\n\n\n", "meta": {"hexsha": "43c8c6d5aeab9ef064888cc933f40ef9dab427e9", "size": 2971, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/regression.cpp", "max_stars_repo_name": "O-Pelumi/gradientdescent", "max_stars_repo_head_hexsha": "b889d58e89e6f0d9ba3f9e735908e67d5cb55e9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/regression.cpp", "max_issues_repo_name": "O-Pelumi/gradientdescent", "max_issues_repo_head_hexsha": "b889d58e89e6f0d9ba3f9e735908e67d5cb55e9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/regression.cpp", "max_forks_repo_name": "O-Pelumi/gradientdescent", "max_forks_repo_head_hexsha": "b889d58e89e6f0d9ba3f9e735908e67d5cb55e9e", "max_forks_repo_licenses": ["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.8347826087, "max_line_length": 108, "alphanum_fraction": 0.5711881521, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.8499711832583695, "lm_q1q2_score": 0.7950175812584487}} {"text": "#pragma once\n#include \"coordinate_transform.hpp\"\n#include \"grad_shape.hpp\"\n#include \"integrate.hpp\"\n#include \"shape.hpp\"\n#include \n#include \n\n//----------------compMatrixBegin----------------\n//! Evaluate the stiffness matrix on the triangle spanned by\n//! the points (a, b, c).\n//!\n//! Here, the stiffness matrix A is a 3x3 matrix\n//!\n//! $$A_{ij} = \\int_{K} (\\nabla \\lambda_i^K(x, y) \\cdot \\nabla \\lambda_j^K(x, y) dV$$\n//!\n//! where $K$ is the triangle spanned by (a, b, c).\n//!\n//! @param[out] stiffnessMatrix should be a 3x3 matrix\n//! At the end, will contain the integrals above.\n//!\n//! @param[in] a the first corner of the triangle\n//! @param[in] b the second corner of the triangle\n//! @param[in] c the third corner of the triangle\n//! @param[in] sigma the function sigma as in the exercise\n//! @param[in] r the parameter r as in the exercise\ntemplate \nvoid computeStiffnessMatrix(MatrixType & stiffnessMatrix,\n const Point &a,\n const Point &b,\n const Point &c) {\n\tEigen::Matrix2d coordinateTransform = makeCoordinateTransform(b - a, c - a);\n\tdouble volumeFactor = std::abs(coordinateTransform.determinant());\n\n\tEigen::Matrix2d elementMap = coordinateTransform.inverse().transpose();\n\t// (write your solution here)\n\tstiffnessMatrix.resize(3, 3);\n\n\tfor (int i = 0; i < 3; ++i) {\n\t\tfor (int j = 0; j < 3; ++j) {\n\t\t\tauto f = [&](double x, double y) -> double {\n\t\t\t\tEigen::Vector2d gradLambdaI = elementMap * gradientLambda(i, x, y);\n\t\t\t\tEigen::Vector2d gradLambdaJ = elementMap * gradientLambda(j, x, y);\n\n\t\t\t\treturn gradLambdaI.dot(gradLambdaJ);\n\t\t\t};\n\n\t\t\tstiffnessMatrix(i, j) = volumeFactor * integrate2d(f);\n\t\t}\n\t}\n}\n//----------------compMatrixEnd----------------\n", "meta": {"hexsha": "5eb26af0db4d278e7c01b94347ee369013f563cb", "size": 1853, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series4/2d-rad-cooling/stiffness_matrix.hpp", "max_stars_repo_name": "westernmagic/NumPDE", "max_stars_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "series4/2d-rad-cooling/stiffness_matrix.hpp", "max_issues_repo_name": "westernmagic/NumPDE", "max_issues_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-04-01T22:52:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T16:21:55.000Z", "max_forks_repo_path": "series4/2d-rad-cooling/stiffness_matrix.hpp", "max_forks_repo_name": "westernmagic/NumPDE", "max_forks_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9622641509, "max_line_length": 86, "alphanum_fraction": 0.6168375607, "num_tokens": 488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422269175636, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.794663673981633}} {"text": "#pragma once\n//! c/c++ headers\n#include \n//! dependency headers\n#include \n//! project headers\n\n/**\n * @brief Construct roll-pitch-yaw rotation matrix from angles\n *\n * @param [in] yaw rotation angle about z-axis\n * @param [in] pitch rotation angle about y-axis\n * @param [in] roll rotation angle about x-axis\n * @param [out] R rpy rotation matrix\n * @return\n */\nvoid make_euler(double const & yaw, double const & pitch, double const & roll, arma::mat33 & R) {\n //! yaw\n auto const & psi = yaw;\n double const s_psi = std::sin(psi);\n double const c_psi = std::cos(psi);\n arma::mat33 const Ry = {{c_psi, -s_psi, 0}, {s_psi, c_psi, 0}, {0, 0, 1}};\n //! pitch\n auto const & theta = pitch;\n double const s_theta = std::sin(theta);\n double const c_theta = std::cos(theta);\n arma::mat33 const Rp = {{c_theta, 0, s_theta}, {0, 1, 0}, {-s_theta, 0, c_theta}};\n //! roll\n auto const & phi = roll;\n double const s_phi = std::sin(phi);\n double const c_phi = std::cos(phi);\n arma::mat33 const Rr = {{1, 0, 0}, {0, c_phi, -s_phi}, {0, s_phi, c_phi}};\n\n //! rpy sequence\n R = Ry * Rp * Rr;\n}\n\n/**\n * @brief Compute Euler angles from rotation matrix\n *\n * @param [in] R rpy rotation matrix\n * @param [out] angles column vector with (roll, pitch, yaw) angles of rpy rotation sequence\n * @param [in] flip_pitch (optional, default=false) use alternate convention for pitch angle\n * @return\n *\n * @note this routine assumes input matrix is a valid rotation matrix\n */\nvoid find_euler_angles(arma::mat33 const & R, arma::vec3 & angles, bool flip_pitch = false) {\n auto const & r_31 = R(2, 0);\n if (std::abs(r_31 - 1.0) <= std::numeric_limits::epsilon() ||\n std::abs(r_31 + 1.0) <= std::numeric_limits::epsilon()) {\n //! gimbal lock condition\n angles(2) = static_cast(0);\n if (r_31 < 0) {\n angles(1) = 0.5 * M_PI;\n angles(0) = angles(2) + std::atan2(R(0, 1), R(0, 2));\n } else {\n angles(1) = -0.5 * M_PI;\n angles(0) = -angles(2) + std::atan2(-R(0, 1), -R(0, 2));\n }\n } else {\n if (flip_pitch) {\n angles(1) = M_PI + std::asin(r_31);\n } else {\n angles(1) = -std::asin(r_31);\n }\n angles(0) = std::atan2(R(2, 1) / std::cos(angles(0)), R(2, 2) / std::cos(angles(0)));\n angles(2) = std::atan2(R(1, 0) / std::cos(angles(0)), R(0, 0) / std::cos(angles(0)));\n }\n}\n", "meta": {"hexsha": "67e818a8989427056c5e6abf11d1544b9abb9f1d", "size": 2361, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/transforms/test_utilities.hpp", "max_stars_repo_name": "jwdinius/nmsac", "max_stars_repo_head_hexsha": "b765be4340cf8367e1af345dc156597ce425c818", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/transforms/test_utilities.hpp", "max_issues_repo_name": "jwdinius/nmsac", "max_issues_repo_head_hexsha": "b765be4340cf8367e1af345dc156597ce425c818", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2020-07-19T23:38:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-14T22:36:30.000Z", "max_forks_repo_path": "tests/transforms/test_utilities.hpp", "max_forks_repo_name": "jwdinius/nmsac", "max_forks_repo_head_hexsha": "b765be4340cf8367e1af345dc156597ce425c818", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-06T06:59:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-06T06:59:04.000Z", "avg_line_length": 33.2535211268, "max_line_length": 97, "alphanum_fraction": 0.6060991105, "num_tokens": 805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8757869803008764, "lm_q1q2_score": 0.7946122349254334}} {"text": "/* Main routine to run an implicit midpoint finite-difference method for solution \n of a second-order, scalar-valued BVP:\n\n u'' = p(t)*u' + q(t)*u + r(t), a\n#include \n#include \n#include \n#include \"bvp.hpp\"\n\nusing namespace std;\nusing namespace arma;\n\n// main routine\nint main(int argc, char **argv) {\n\n // get lambda from the command line, otherwise set to -10\n double lambda;\n if (argc > 1)\n lambda = atof(argv[1]);\n if (lambda >= 0.0)\n lambda = -10.0;\n\n // define BVP object\n BVP bvp(lambda);\n\n // loop over spatial resolutions for tests\n vector N = {100, 1000, 10000};\n for (int i=0; i\n#include \n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n cout.precision(3);\n MatrixXd A(3,3);\nA << 4,-1,2, -1,6,0, 2,0,5;\ncout << \"The matrix A is\" << endl << A << endl;\n\nLLT lltOfA(A); // compute the Cholesky decomposition of A\nMatrixXd L = lltOfA.matrixL(); // retrieve factor L in the decomposition\n// The previous two lines can also be written as \"L = A.llt().matrixL()\"\n\ncout << \"The Cholesky factor L is\" << endl << L << endl;\ncout << \"To check this, let us compute L * L.transpose()\" << endl;\ncout << L * L.transpose() << endl;\ncout << \"This should equal the matrix A\" << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "a498cf9cd1c45595d5f805027c8a5edff4e1d9a4", "size": 670, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_LLT_example.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_LLT_example.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_LLT_example.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": 26.8, "max_line_length": 73, "alphanum_fraction": 0.6447761194, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065458, "lm_q2_score": 0.8397339676722394, "lm_q1q2_score": 0.7935441586906218}} {"text": "#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\nusing namespace NTL;\r\nusing namespace std;\r\n\r\nclass RSA{\r\nprivate:\r\n ZZ p;\r\n ZZ q;\r\n ZZ d;\r\n ZZ N;\r\n ZZ e;\r\n ZZ o;\r\n string abc=\"abcdefghijklmnopqrstuvwxyz \";\r\npublic:\r\n RSA();\r\n RSA(int n_digi);\r\n string RSA_encripta();\r\n string RSA_descifra();\r\n ZZ aleatorio(int num_digits2);\r\n ZZ modulo(ZZ a,ZZ b);\r\n ZZ eucl_ext(ZZ a,ZZ b);\r\n ZZ mcd(ZZ a,ZZ b);\r\n ZZ exp(ZZ base,ZZ exponente);\r\n ZZ exp_mod(ZZ base, ZZ exponente, ZZ mod);\r\n ZZ resto_chino(ZZ bloque_);\r\n bool Fermat(ZZ n,ZZ t);\r\n ZZ generar_primos(int num_digits);\r\n ZZ get_N(){return N;}\r\n string ZZto_string(ZZ a);\r\n ZZ STRto_ZZ(string str);\r\n string abrir_archivo();\r\n void guardar_archivo(string mensaje);\r\n string agregar_0(ZZ num,int K);\r\n string mensaje_abc(string mensaje,int K);\r\n string abc_mensaje(string mensaje);\r\n};\r\n\r\n/*Valores por defecto*/\r\nRSA::RSA(){\r\n p=17;\r\n q=59;\r\n N=p*q;\r\n o=(p-1)*(q-1);\r\n e=3;\r\n}\r\n\r\n/*Generar p y q de n digitos*/\r\nRSA::RSA(int n_digi){\r\n p=generar_primos(n_digi);\r\n q=generar_primos(n_digi);\r\n N=p*q;\r\n o=(p-1)*(q-1);\r\n e=aleatorio(n_digi/2);\r\n while(mcd(e,o)!=1){\r\n e++;\r\n }\r\n cout<<\"p:\"<(K-1)){\r\n while(mensaje_.size()%(K-1)!=0){\r\n mensaje_=mensaje_+\"26\";\r\n }\r\n }\r\n else{\r\n stringstream ss;\r\n ss<0){\r\n r=modulo(a,b);\r\n a=b;\r\n b=r;\r\n }\r\n }\r\n return a;\r\n}\r\n\r\n/*Euclides extendido*/\r\nZZ RSA::eucl_ext(ZZ a,ZZ b){\r\n ZZ a_inicial;a_inicial=a;\r\n ZZ t1,t2,r,q;t1=0,t2=1,r=1,q=0;\r\n ZZ t;t=0;\r\n while(r>0){\r\n q=a/b;\r\n r=a-q*b;\r\n a=b;\r\n b=r;\r\n t=t2;\r\n t2=t1-(q*t2);\r\n t1=t;\r\n }\r\n if(t1<0){\r\n t1=t1+a_inicial;\r\n }\r\n return t1;\r\n}\r\n\r\n/*Funcion exponencial*/\r\nZZ RSA::exp(ZZ base,ZZ exponente){\r\n ZZ resultado;resultado=1;\r\n while(exponente!=0){\r\n if(exponente-((exponente>>1)<<1)==1){\r\n resultado=base*resultado;\r\n }\r\n base=base*base;\r\n exponente=exponente>>1;\r\n }\r\n return resultado;\r\n\r\n}\r\n\r\n/*Exponenciacion modular*/\r\nZZ RSA::exp_mod(ZZ base,ZZ exponente,ZZ mod){\r\n ZZ resultado;resultado=1;\r\n while(exponente!=0){\r\n base=modulo(base,mod);\r\n if(exponente-((exponente>>1)<<1)==1){\r\n resultado=modulo(base*resultado,mod);\r\n }\r\n base=base*base;\r\n exponente=exponente>>1;\r\n }\r\n return resultado;\r\n}\r\n\r\n/*Teorema del resto chino*/\r\nZZ RSA::resto_chino(ZZ bloque_){\r\n d=eucl_ext((p-1)*(q-1),e);\r\n ZZ dp,dq,p1,p2,q1,q2;\r\n dp=modulo(d,(p-1));\r\n dq=modulo(d,(q-1));\r\n p1=N/p;\r\n q1=eucl_ext(p1,p);\r\n p2=N/q;\r\n q2=eucl_ext(p2,q);\r\n ZZ a;a=exp(bloque_,dp);\r\n ZZ b;b=exp(bloque_,dq);\r\n //cout<<\"dp \"<\n#include \n#include \n#include \n#include \n\nnamespace mathtoolbox\n{\n /// \\brief An abstract class for helping define custom kernel functor classes\n class AbstractRbfKernel\n {\n public:\n AbstractRbfKernel() {}\n virtual ~AbstractRbfKernel(){};\n\n /// \\brief Perform RBF evaluation\n virtual double operator()(const double r) const = 0;\n };\n\n class GaussianRbfKernel final : public AbstractRbfKernel\n {\n public:\n GaussianRbfKernel(const double theta = 1.0) : m_theta(theta) {}\n\n double operator()(const double r) const override\n {\n assert(r >= 0.0);\n return std::exp(-m_theta * r * r);\n }\n\n private:\n const double m_theta;\n };\n\n /// \\details This kernel is also known as the polyharmonic kernel with k = 1\n class LinearRbfKernel final : AbstractRbfKernel\n {\n public:\n LinearRbfKernel() {}\n\n double operator()(const double r) const override\n {\n assert(r >= 0.0);\n return r;\n }\n };\n\n /// \\details This kernel is also known as the polyharmonic kernel with k = 2\n class ThinPlateSplineRbfKernel final : public AbstractRbfKernel\n {\n public:\n ThinPlateSplineRbfKernel() {}\n\n double operator()(const double r) const override\n {\n assert(r >= 0.0);\n const double value = r * r * std::log(r);\n return std::isnan(value) ? 0.0 : value;\n }\n };\n\n /// \\details This kernel is also known as the polyharmonic kernel with k = 3\n class CubicRbfKernel final : public AbstractRbfKernel\n {\n public:\n CubicRbfKernel() {}\n\n double operator()(const double r) const override\n {\n assert(r >= 0.0);\n return r * r * r;\n }\n };\n\n class RbfInterpolator\n {\n public:\n RbfInterpolator(const std::function& rbf_kernel = ThinPlateSplineRbfKernel(),\n const bool use_polynomial_term = true);\n\n /// \\brief Set data points and their values\n void SetData(const Eigen::MatrixXd& X, const Eigen::VectorXd& y);\n\n /// \\brief Calculate the interpolation weights\n ///\n /// \\details This method should be called after setting the data\n void CalcWeights(const bool use_regularization = false, const double lambda = 0.001);\n\n /// \\brief Calculate the interpolatetd value at the specified data point\n ///\n /// \\details This method should be called after calculating the weights\n double CalcValue(const Eigen::VectorXd& x) const;\n\n private:\n /// \\brief The RBF kernel\n const std::function m_rbf_kernel;\n\n /// \\brief The polynomial term setting\n const bool m_use_polynomial_term;\n\n /// \\brief Data locations\n Eigen::MatrixXd m_X;\n\n /// \\brief Data values\n Eigen::VectorXd m_y;\n\n /// \\brief Weights for the RBF kernel values\n Eigen::VectorXd m_w;\n\n /// \\brief Weights for the polynomial terms\n Eigen::VectorXd m_v;\n };\n} // namespace mathtoolbox\n\n#endif // MATHTOOLBOX_RBF_INTERPOLATION_HPP\n", "meta": {"hexsha": "56f21b260acaf3fdfd89cd35a9dba01b7a24b92c", "size": 3368, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/rbf-interpolation.hpp", "max_stars_repo_name": "yuki-koyama/mathtoolbox", "max_stars_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 195.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T16:12:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:52:56.000Z", "max_issues_repo_path": "include/mathtoolbox/rbf-interpolation.hpp", "max_issues_repo_name": "yuki-koyama/mathtoolbox", "max_issues_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2018-04-15T01:24:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T09:14:23.000Z", "max_forks_repo_path": "include/mathtoolbox/rbf-interpolation.hpp", "max_forks_repo_name": "yuki-koyama/mathtoolbox", "max_forks_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T04:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:28:12.000Z", "avg_line_length": 28.3025210084, "max_line_length": 116, "alphanum_fraction": 0.6039192399, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.8688267694452331, "lm_q1q2_score": 0.7927489678384797}} {"text": "//\n// Created by egordm on 26-7-2018.\n//\n\n#ifndef PROJECT_MATH_UTILS_HPP\n#define PROJECT_MATH_UTILS_HPP\n\n#include \"defines.h\"\n#include \n#include \n\nusing namespace sp;\nusing namespace arma;\n\nnamespace libtempo { namespace utils { namespace math {\n\n inline int fix(double x) {\n return static_cast(x >= 0 ? floor(x) : ceil(x));\n }\n\n inline vec sinc_fac(const vec &x) {\n vec ret(x.size());\n for(uword i = 0; i < x.size(); ++i) {\n if (fabs(x.at(i)) < EPSILON) ret.at(i) = 1;\n else ret.at(i) = sin(M_PI * x.at(i)) / (M_PI * x.at(i));\n }\n\n return ret;\n }\n\n inline arma::vec my_hanning( const arma::uword N ) {\n arma::vec h(N);\n for(arma::uword i=0; i 0) {\n tmp = n1;\n n1 = n2 % n1;\n n2 = tmp;\n }\n return n2;\n }\n\n inline int quotient_ceil(int n1, int n2) {\n if (n1 % n2 != 0) return n1 / n2 + 1;\n return n1 / n2;\n }\n}}}\n\n#endif //PROJECT_MATH_UTILS_HPP\n", "meta": {"hexsha": "153bab82462558ca9286d48b870937b44b186b52", "size": 1213, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libtempo/math_utils.hpp", "max_stars_repo_name": "EgorDm/libtempo", "max_stars_repo_head_hexsha": "06fa7d440157b4507261b22896e0d8dd0fb5a85e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-12-21T11:21:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-20T03:00:19.000Z", "max_issues_repo_path": "libtempo/math_utils.hpp", "max_issues_repo_name": "EgorDm/libtempo", "max_issues_repo_head_hexsha": "06fa7d440157b4507261b22896e0d8dd0fb5a85e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libtempo/math_utils.hpp", "max_forks_repo_name": "EgorDm/libtempo", "max_forks_repo_head_hexsha": "06fa7d440157b4507261b22896e0d8dd0fb5a85e", "max_forks_repo_licenses": ["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.6607142857, "max_line_length": 68, "alphanum_fraction": 0.5086562242, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951680216529, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7923369742713876}} {"text": "/** @file 20.cpp Problem 20: Factorial digit sum\n *\n * n! means n x (n - 1) x ... x 3 x 2 x 1\n *\n * For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800, and the sum of the\n * digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.\n *\n * Find the sum of the digits in the number 100!\n */\n\n#include \"cpp_int_util.hpp\" // sum_digits\n\n/// @cond\n#include // cpp_int\n\n#include // assert\n#include // cout\n/// @endcond\n\nusing boost::multiprecision::cpp_int;\n\nint sum(int n)\n{\n cpp_int p = 1;\n for (int i = 2; i <= n; ++i)\n p *= i;\n return cpp_int_util::sum_digits(p);\n}\n\nint main()\n{\n assert(sum(10) == 27);\n std::cout << sum(100) << std::endl;\n}\n", "meta": {"hexsha": "7ac6dd409f1f07a40d82d55af542646f708c3513", "size": 740, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/20.cpp", "max_stars_repo_name": "jeffs/cpp-euler", "max_stars_repo_head_hexsha": "b42a8a70fad782569a699a028968bc1a60bd5c44", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/20.cpp", "max_issues_repo_name": "jeffs/cpp-euler", "max_issues_repo_head_hexsha": "b42a8a70fad782569a699a028968bc1a60bd5c44", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/20.cpp", "max_forks_repo_name": "jeffs/cpp-euler", "max_forks_repo_head_hexsha": "b42a8a70fad782569a699a028968bc1a60bd5c44", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1428571429, "max_line_length": 76, "alphanum_fraction": 0.5648648649, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765304654121, "lm_q2_score": 0.8670357701094303, "lm_q1q2_score": 0.792190234222991}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \"time.h\"\n\nusing namespace std; // note use of namespace\nusing namespace arma; // note use of namespace\nint main (int argc, char* argv[])\n{\n // read in dimension of square matrix\n int n = atoi(argv[1]);\n auto s = 1/sqrt( (double) n);\n // Start timing\n clock_t start, finish;\n // Allocate space for the three matrices\n mat A(n,n), B(n,n), C(n,n);\n // Set up values for matrix A and B\n for (auto i = 0; i < n; i++){\n for (auto j = 0; j < n; j++) {\n double angle = 2.0*M_PI*i*j/ (( double ) n);\n A(i,j) = s * ( sin ( angle ) + cos ( angle ) );\n B(j,i) = A(i,j);\n }\n }\n C = 0.0;\n // Then perform the matrix-matrix multiplication using DGEMM\n start = clock();\n C = A*B;\n auto TraceMat = trace(C);\n finish = clock();\n double timeused = (double) (finish - start)/(CLOCKS_PER_SEC );\n cout << setiosflags(ios::showpoint | ios::uppercase);\n cout << setprecision(10) << setw(20) << \"Time used for matrix-matrix multiplication=\" << timeused << endl;\n cout << setprecision(10) << setw(20) << \"Trace of Matrix=\" << TraceMat << endl;\n return 0;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "34774af2f9a86c6c0e5dab0d764896e386332d68", "size": 1215, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/Programs/LecturePrograms/programs/Classes/cpp/program16.cpp", "max_stars_repo_name": "solisius/ComputationalPhysics", "max_stars_repo_head_hexsha": "94d32d177881695d443eea34af3410e886b8cb9a", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 220.0, "max_stars_repo_stars_event_min_datetime": "2016-08-25T09:18:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:09:16.000Z", "max_issues_repo_path": "doc/Programs/LecturePrograms/programs/Classes/cpp/program16.cpp", "max_issues_repo_name": "solisius/ComputationalPhysics", "max_issues_repo_head_hexsha": "94d32d177881695d443eea34af3410e886b8cb9a", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-04T12:55:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-04T12:55:10.000Z", "max_forks_repo_path": "doc/Programs/LecturePrograms/programs/Classes/cpp/program16.cpp", "max_forks_repo_name": "solisius/ComputationalPhysics", "max_forks_repo_head_hexsha": "94d32d177881695d443eea34af3410e886b8cb9a", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 136.0, "max_forks_repo_forks_event_min_datetime": "2016-08-25T09:04:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T09:54:21.000Z", "avg_line_length": 22.0909090909, "max_line_length": 110, "alphanum_fraction": 0.6008230453, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7921675066220835}} {"text": "#include \r\n#include \r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\nint main()\r\n{\r\n Matrix2f A, b;\r\n LLT llt;\r\n A << 2, -1, -1, 3;\r\n b << 1, 2, 3, 1;\r\n cout << \"Here is the matrix A:\\n\" << A << endl;\r\n cout << \"Here is the right hand side b:\\n\" << b << endl;\r\n cout << \"Computing LLT decomposition...\" << endl;\r\n llt.compute(A);\r\n cout << \"The solution is:\\n\" << llt.solve(b) << endl;\r\n A(1,1)++;\r\n cout << \"The matrix A is now:\\n\" << A << endl;\r\n cout << \"Computing LLT decomposition...\" << endl;\r\n llt.compute(A);\r\n cout << \"The solution is now:\\n\" << llt.solve(b) << endl;\r\n}\r\n", "meta": {"hexsha": "ab1a1a839e1c7a38565164bffe9b9e4939c97c2e", "size": 645, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/TutorialLinAlgComputeTwice.cpp", "max_stars_repo_name": "k4rth33k/dnnc-operators", "max_stars_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T14:35:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-11T23:59:22.000Z", "max_issues_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/TutorialLinAlgComputeTwice.cpp", "max_issues_repo_name": "k4rth33k/dnnc-operators", "max_issues_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-08-12T04:38:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T16:32:13.000Z", "max_forks_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/TutorialLinAlgComputeTwice.cpp", "max_forks_repo_name": "k4rth33k/dnnc-operators", "max_forks_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-08-15T13:29:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-09T17:08:04.000Z", "avg_line_length": 26.875, "max_line_length": 61, "alphanum_fraction": 0.5410852713, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692236, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7918873550862551}} {"text": "#include \n\n#include \n#include \n\nusing namespace Eigen;\n\n//!\n//! \\brief buildDistanceLSQMatrix Efficiently build the system matrix\n//! mapping positions to distances.\n//! \\param n Number of points (including $x_1$).\n//! \\return The system matrix $A$.\n//!\n\nSparseMatrix buildDistanceLSQMatrix(int n) {\n\tSparseMatrix A(n*(n-1)/2, n-1);\n\n\tstd::vector> triplets;\n\n\tint row = 0;\n\tfor(int i = 0; i < n - 1; i++) {\n\t\tfor(int j = i; j < n - 1; j++) {\n\t\t\ttriplets.push_back(Triplet(row, j, 1));\n\t\t\tif(i > 0) {\n\t\t\t\ttriplets.push_back(Triplet(row, i - 1, -1));\t\t\t\n\t\t\t}\n\t\t\trow++;\n\t\t}\n\t}\n\t\n\tA.setFromTriplets(triplets.begin(), triplets.end());\n\tA.makeCompressed();\n\treturn A;\n}\n\n\n//!\n//! \\brief estimatePointsPositions Return positions (without $x_1$).\n//! The coordinate $x_1$ is assumed $x_1 = 0$.\n//! \\param D An $n \\times n$ anti-symmetric matrix of distances.\n//! \\return Vector of positions $x_2, \\dots, x_n$.\n//!\n\nVectorXd estimatePointsPositions(const MatrixXd& D) {\n\n\tVectorXd x;\n\tint n = D.rows();\n\tVectorXd b(n * (n - 1) / 2);\n\n\t// get matrix A\n\tSparseMatrix A = buildDistanceLSQMatrix(n);\n\n\t// transform matrix D into vector with distance entries\n\tint idx = 0;\t\n\tfor(int i = 0; i < n; i++) {\n\t\tfor(int j = i + 1; j < n; j++) {\n\t\t\tb(idx++) = -D(i, j);\t\t\n\t\t}\n\t}\n\t\n\t// Solve sparse LSQ with normal equations\n\tSparseLU> lu(A.transpose() * A);\n\tx = lu.solve(A.transpose() * b);\t\n\n\treturn x;\n}\n\n\nint main() {\n \n int n = 5;\n \n // PART 1: build and print system matrix A\n std::cout << \"**** PART 1 ****\" << std::endl;\n std::cout << \"The Matrix A is:\"\n << std::endl\n << buildDistanceLSQMatrix(n)\n << std::endl;\n\n // PART 2: solve the LSQ system and find positions\n std::cout << \"**** PART 2 ****\" << std::endl;\n // Vector of positions\n n = 5;\n\n // Build D\n MatrixXd D(n,n);\n D << 0, -2.1, -3, -4.2, -5,\n 2.1, 0, -0.9, -2.2, -3.3,\n 3, 0.9, 0, -1.3, -1.1,\n 4.2, 2.2, 1.3, 0, -1.1,\n 5, 3.3, 1.1, 1.1, 0;\n std::cout << \"The matrix D is:\"\n << std::endl\n << D\n << std::endl;\n\n // Find out positions\n VectorXd x_recovered = estimatePointsPositions(D);\n std::cout << \"The positions [x_2, ..., x_n] obtained from the LSQ system are:\"\n << std::endl\n << x_recovered\n << std::endl;\n}\n", "meta": {"hexsha": "e08a55651c590e71c3cce12643612513b823a1a6", "size": 2499, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mockExam/ex_llsq/estimatePositions.cpp", "max_stars_repo_name": "azurite/numCSE18-code", "max_stars_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-13T19:08:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-13T19:08:32.000Z", "max_issues_repo_path": "mockExam/ex_llsq/estimatePositions.cpp", "max_issues_repo_name": "azurite/numCSE18-code", "max_issues_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mockExam/ex_llsq/estimatePositions.cpp", "max_forks_repo_name": "azurite/numCSE18-code", "max_forks_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_forks_repo_licenses": ["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.0288461538, "max_line_length": 82, "alphanum_fraction": 0.5478191277, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404116305639, "lm_q2_score": 0.8519528057272544, "lm_q1q2_score": 0.7918393664449531}} {"text": "// advent2019_22.cpp : This file contains the 'main' function. Program execution begins and ends there.\n//\n\n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace std;\n\n// C function for extended Euclidean Algorithm \n__int64 gcdExtended(__int64 a, __int64 b, __int64* x, __int64* y);\n\n// Function to find modulo inverse of a \n__int64 modInverse(__int64 a, __int64 m)\n{\n __int64 x, y;\n __int64 g = gcdExtended(a, m, &x, &y);\n if (g != 1)\n throw exception(\"Inverse doesn't exist\");\n else\n {\n // m is added to handle negative x \n return (x % m + m) % m;\n }\n}\n\n// C function for extended Euclidean Algorithm \n__int64 gcdExtended(__int64 a, __int64 b, __int64* x, __int64* y)\n{\n // Base Case \n if (a == 0)\n {\n *x = 0, * y = 1;\n return b;\n }\n\n __int64 x1, y1; // To store results of recursive call \n __int64 gcd = gcdExtended(b % a, a, &x1, &y1);\n\n // Update x and y using results of recursive \n // call \n *x = y1 - (b / a) * x1;\n *y = x1;\n\n return gcd;\n}\n\n\n\n\ntypedef vector Commands;\n\nstruct Linear {\n __int64 mult;\n __int64 add;\n Linear() : mult(1), add(0) {}\n Linear(__int64 m, __int64 a) : mult(m), add(a) {}\n};\n\nvoid NewStack(Linear& linear, __int64 m)\n{\n linear.mult = -linear.mult + m;\n linear.add = -linear.add - 1;\n while (linear.add < 0) linear.add += m;\n}\n\nvoid Cut(Linear& linear, __int64 n, __int64 m)\n{\n linear.add = linear.add - n;\n if (linear.add >= m) linear.add -= m;\n if (linear.add < 0) linear.add += m;\n}\n\n__int64 MultMod(__int64 a, __int64 b, __int64 m)\n{\n boost::multiprecision::int128_t a128(a);\n boost::multiprecision::int128_t b128(b);\n boost::multiprecision::int128_t r = a128 * b128;\n r %= m;\n return static_cast<__int64>(r);\n}\n\nvoid DealIncr(Linear& linear, __int64 n, __int64 m)\n{\n linear.mult = MultMod(linear.mult, n, m);\n linear.add = MultMod(linear.add, n, m);\n}\n\n__int64 NewPos(Linear& linear, __int64 p, __int64 m)\n{\n p = MultMod(linear.mult, p, m);\n p += linear.add;\n if (p >= m) p -= m;\n if (p < 0) p += m;\n return p;\n}\n\nLinear Invert(const Linear& linear, __int64 m)\n{\n __int64 d = modInverse(linear.mult, m);\n Linear r( d, -MultMod(d, linear.add, m) );\n if (r.add < 0) r.add += m;\n return r;\n}\n\n__int64 Power(__int64 b, __int64 e, __int64 m)\n{\n if (e == 0) return 1;\n if (e == 1) return b % m;\n\n __int64 t = Power(b, e / 2, m);\n t = MultMod(t, t, m);\n\n if (e % 2 == 0) return t;\n else return MultMod(b, t, m);\n}\n\nLinear Repeat(const Linear& linear, __int64 rpt, __int64 m)\n{\n // A^n*x + (A^n-1) / (A-1) * B, from https://www.reddit.com/r/adventofcode/comments/ee0rqi/2019_day_22_solutions/fbnifwk/\n // Yes, I had to look up the solution. So annoyed because I was so close and should\n // have been able to figure this out.\n __int64 mult = Power(linear.mult, rpt, m);\n __int64 add = mult - 1;\n add = MultMod(add, modInverse(linear.mult - 1, m), m);\n add = MultMod(add, linear.add, m);\n Linear r(mult, add);\n return r;\n}\n\nLinear Convert(const Commands& commands, __int64 m)\n{\n Linear lin;\n for (auto c : commands) {\n if (c == \"deal into new stack\"s) NewStack(lin, m);\n else if (c.substr(0, 3) == \"cut\"s) {\n int n = atoi(c.substr(4).c_str());\n Cut(lin, n, m);\n }\n else if (c.substr(0, 19) == \"deal with increment\"s) {\n int n = atoi(c.substr(20).c_str());\n DealIncr(lin, n, m);\n }\n }\n\n return lin;\n}\n\n__int64 Part1(const Commands& commands, __int64 pos, __int64 m)\n{\n Linear lin = Convert(commands, m);\n pos = NewPos(lin, pos, m);\n return pos;\n}\n\n__int64 Part2(const Commands& commands, __int64 pos, __int64 m, __int64 rpt)\n{\n Linear lin = Convert(commands, m);\n lin = Invert(lin, m);\n lin = Repeat(lin, rpt, m);\n pos = NewPos(lin, pos, m);\n return pos;\n}\n\nint main()\n{\n Commands commands;\n ifstream f(\"Data.txt\");\n while (!f.eof()) {\n string s;\n getline(f, s);\n commands.push_back(s);\n }\n\n __int64 pos;\n\n pos = Part1(commands, 2019, 10007);\n cout << \"Part 1: \" << pos << endl;\n\n pos = Part2(commands, pos, 10007, 1);\n cout << \"Reverse Check: \" << pos << endl << endl;\n\n pos = Part1(commands, 2019, 10007);\n pos = Part1(commands, pos, 10007);\n pos = Part1(commands, pos, 10007);\n pos = Part1(commands, pos, 10007);\n pos = Part1(commands, pos, 10007);\n cout << \"Part 1*5: \" << pos << endl;\n\n pos = Part2(commands, pos, 10007, 5);\n cout << \"Reverse Check: \" << pos << endl;\n\n pos = Part2(commands, 2020, 119315717514047i64, 101741582076661i64);\n cout << \"Part 2: \" << pos << endl;\n}\n", "meta": {"hexsha": "777a39d8c22b7249e1fb8ba0b687a30af30977eb", "size": 4804, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "advent2019_22/advent2019_22.cpp", "max_stars_repo_name": "throx/advent2019", "max_stars_repo_head_hexsha": "b3d4929fe501c72fb9b7db854b08fda119d6cda9", "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": "advent2019_22/advent2019_22.cpp", "max_issues_repo_name": "throx/advent2019", "max_issues_repo_head_hexsha": "b3d4929fe501c72fb9b7db854b08fda119d6cda9", "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": "advent2019_22/advent2019_22.cpp", "max_forks_repo_name": "throx/advent2019", "max_forks_repo_head_hexsha": "b3d4929fe501c72fb9b7db854b08fda119d6cda9", "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.1407035176, "max_line_length": 125, "alphanum_fraction": 0.5870108243, "num_tokens": 1559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474155747541, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7913442930508008}} {"text": "#include \n#include \n\n#include \n#include \"timer.h\"\n\n//! \\brief Circular shift (downwards) of b\n//! \\param[in,out] b Vector is nx1, shifted downwards\ntemplate \nvoid shift(Vector & b) {\n typedef typename Vector::Scalar Scalar;\n int n = b.size();\n \n Scalar temp = b(n-1);\n for(int k = n-2; k >= 0; --k) {\n b(k+1) = b(k);\n }\n b(0) = temp;\n}\n\n//! \\brief Compute X = inv(A)*[b_1,...,b_n], b_i = i-th cyclic shift of b\n//! \\param[in] A Matrix is nx\n//! \\param[in] b Vector is nx1\n//! \\param[out] X solution nxn matrix X = inv(A)*[b_1,...,b_n]\ntemplate \nvoid solvpermb(const Matrix & A, Vector & b, Matrix & X) {\n // Size of b, which is size of A\n int n = b.size();\n if( n != A.cols() or n != A.rows() ) {\n // Size check, error if do not match\n std::cerr << \"Error: size mismatch!\" << std::endl;\n return;\n }\n X.resize(n,n);\n \n for(int l = 0; l < n; ++l) {\n X.col(l) = A.fullPivLu().solve(b);\n \n shift(b);\n }\n}\n\n//! \\brief Compute X = inv(A)*[b_1,...,b_n], b_i = i-th cyclic shift of b in O(n^3)\n//! \\param[in] A Matrix is nx\n//! \\param[in] b Vector is nx1\n//! \\param[out] X solution nxn matrix X = inv(A)*[b_1,...,b_n]\ntemplate \nvoid solvpermb_on3(const Matrix & A, Vector & b, Matrix & X) {\n // Size of b, which is size of A\n int n = b.size();\n if( n != A.cols() or n != A.rows() ) {\n // Size check, error if do not match\n std::cerr << \"Error: size mismatch!\" << std::endl;\n return;\n }\n X.resize(n,n);\n \n // Notice here we reuse the LU factorization\n Eigen::FullPivLU LU = A.fullPivLu();\n \n for(int l = 0; l < n; ++l) {\n X.col(l) = LU.solve(b);\n \n shift(b);\n }\n}\n \nint main() {\n unsigned int n = 9;\n // Compute with both LU and reuse LU\n std::cout << \"*** Check correctness of permutation solver\" << std::endl;\n Eigen::MatrixXd A = Eigen::MatrixXd::Random(n,n);\n Eigen::VectorXd b = Eigen::VectorXd::Random(n);\n Eigen::MatrixXd X;\n std::cout << \"b = \" << std::endl << b << std::endl;\n solvpermb(A,b,X);\n std::cout << \"Direct porting from MALTAB: \" << std::endl << X << std::endl;\n std::cout << \"A*X = \" << std::endl << A*X << std::endl;\n solvpermb_on3(A,b,X);\n std::cout << \"Reusing LU: \" << std::endl << X << std::endl;\n std::cout << \"A*X = \" << std::endl << A*X << std::endl;\n \n // Compute runtime of different implementations of kron\n std::cout << \"*** Runtime comparisons of LU vs reuse LU\" << std::endl;\n unsigned int repeats = 3;\n timer<> tm_lu, tm_reuse_lu;\n \n for(unsigned int p = 2; p <= 7; p++) {\n tm_lu.reset();\n tm_reuse_lu.reset();\n for(unsigned int r = 0; r < repeats; ++r) {\n unsigned int M = pow(2,p);\n A = Eigen::MatrixXd::Random(M,M);\n b = Eigen::VectorXd::Random(M);\n \n tm_lu.start();\n solvpermb(A,b,X);\n tm_lu.stop();\n \n tm_reuse_lu.start();\n solvpermb_on3(A,b,X);\n tm_reuse_lu.stop();\n }\n \n std::cout << \"LU took: \" << tm_lu.avg().count() / 1000000. << \" ms\" << std::endl;\n std::cout << \"Reuse LU took: \" << tm_reuse_lu.avg().count() / 1000000. << \" ms\" << std::endl;\n }\n}\n", "meta": {"hexsha": "a83bbe28c6a940f0925dc1f9270f33894affb1ce", "size": 3408, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/solutions/solution_2/solvepermb.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/solutions/solution_2/solvepermb.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/solutions/solution_2/solvepermb.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2660550459, "max_line_length": 101, "alphanum_fraction": 0.5228873239, "num_tokens": 1044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.7909825597646416}} {"text": "\r\n#include \"MatricesAndVectors.h\"\r\n#include \"QuatRotEuler.h\"\r\n#include \r\n#include \r\nusing Eigen::Matrix;\r\n\r\n//Rotation matrix around x\r\nMatrix Rotx(double theta){\r\n\tMatrix R;\r\n\r\n\tR << 1, 0, 0,\r\n\t 0, cos(theta), -sin(theta),\r\n\t 0, sin(theta), cos(theta);\r\n\r\n\treturn R;\r\n}\r\n\r\n//Rotation matrix around y\r\nMatrix Roty(double theta){\r\n\tMatrix R;\r\n\r\n\tR << cos(theta), 0, sin(theta),\r\n\t 0, 1, 0,\r\n\t -sin(theta), 0, cos(theta);\r\n\r\n\treturn R;\r\n}\r\n\r\n//Rotation matrix around z\r\nMatrix Rotz(double theta){\r\n\tMatrix R;\r\n\r\n\tR << cos(theta), -sin(theta), 0,\r\n\t sin(theta), cos(theta), 0,\r\n\t 0, 0, 1;\r\n\r\n\treturn R;\r\n}\r\n\r\n//Convert Euler Angles (Roll-pitch-yaw) to Rotation Matrix\r\nMatrix RPY2Rot(double roll, double pitch, double yaw){\r\n\tMatrix Rx = Rotx(roll);\r\n\tMatrix Ry = Roty(pitch);\r\n\tMatrix Rz = Rotz(yaw);\r\n\r\n\treturn Rz*Ry*Rx; //Rout = Rz*Ry*Rx\r\n\t\r\n}\r\n\r\n//Convert quaternion to rotation matrix \r\nMatrix Quat2rot(Matrix q){\r\n\r\n\tMatrix R;\r\n\tdouble qw = q(0);\r\n\tdouble qx = q(1);\r\n\tdouble qy = q(2);\r\n\tdouble qz = q(3);\r\n\r\n\tR << 1 - 2 * pow(qy, 2) - 2 * pow(qz, 2), 2 * qx*qy - 2 * qz*qw, 2 * qx*qz + 2 * qy*qw,\r\n\t 2 * qx*qy + 2 * qz*qw, 1 - 2 * pow(qx, 2) - 2 * pow(qz, 2), 2 * qy*qz - 2 * qx*qw,\r\n\t 2 * qx*qz - 2 * qy*qw, 2 * qy*qz + 2 * qx*qw, 1 - 2 * pow(qx, 2) - 2 * pow(qy, 2);\r\n\r\n\treturn R;\r\n}\r\n\r\n//Convert rotation matrix to quaternion\r\n//http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm\r\nMatrix Rot2quat(Matrix M){\r\n\tdouble trace = M.trace();\r\n\tMatrix q;\r\n\tif (trace > 0) {// M_EPSILON = 0\r\n\t\tdouble s = 0.5 / sqrt(trace + 1.0);\r\n\t\tq << 0.25 / s,\r\n\t\t\t(M(2,1) - M(1,2)) * s,\r\n\t\t\t(M(0,2) - M(2,0)) * s,\r\n\t\t\t(M(1,0) - M(0,1)) * s;\r\n\t}\r\n\telse {\r\n\t\tif (M(0,0) > M(1,1) && M(0,0) > M(2,2)) {\r\n\t\t\tdouble s = 2.0 * sqrt(1.0 + M(0,0) - M(1,1) - M(2,2));\r\n\t\t\tq << (M(2,1) - M(1,2)) / s,\r\n\t\t\t\t 0.25 * s,\r\n\t\t\t\t (M(0,1) + M(1,0)) / s,\r\n\t\t\t\t (M(0,2) + M(2,0)) / s;\r\n\t\t}\r\n\t\telse if (M(1,1) > M(2,2)) {\r\n\t\t\tdouble s = 2.0 * sqrt(1.0 + M(1,1) - M(0,0) - M(2,2));\r\n\t\t\tq << (M(0,2) - M(2,0)) / s;\r\n\t\t\t (M(0,1) + M(1,0)) / s;\r\n\t\t\t 0.25 * s;\r\n\t\t\t (M(1,2) + M(2,1)) / s;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tdouble s = 2.0 * sqrt(1.0 + M(2,2) - M(0,0) - M(1,1));\r\n\t\t\tq << (M(1,0) - M(0,1)) / s;\r\n\t\t\t (M(0,2) + M(2,0)) / s;\r\n\t\t\t (M(1,2) + M(2,1)) / s;\r\n\t\t\t 0.25 * s;\r\n\t\t}\r\n\t}\r\n return q;\r\n}\r\n\r\n//Convert quaternion to Roll-Pitch-Yaw\r\nMatrix Quat2RPY(Matrix q){\r\n\r\n\tMatrix RPY;\r\n\r\n\tRPY << atan2(2*(q(0)*q(1) + q(2)*q(3)) , 1 - 2*(q(1)*q(1) + q(2)*q(2)) ),\t//Roll\r\n\t\t asin(2*(q(0)*q(2) - q(3)*q(1))),\t\t\t\t//Pitch\r\n\t\t atan2(2*(q(0)*q(3) + q(1)*q(2)),1 - 2*(q(2)*q(2) + q(3)*q(3)) );\t//Yaw\r\n\r\n\treturn RPY;\r\n}\r\n\r\n// Quaternion Multiplication\r\nMatrix QuaternionProduct(Matrix q1, Matrix q2){\r\n\tMatrix H;\r\n\tH << q1(0), -q1(1), -q1(2), -q1(3),\r\n\t q1(1), q1(0), -q1(3), q1(2),\r\n\t q1(2), q1(3), q1(0), -q1(1),\r\n\t q1(3), -q1(2), q1(1), q1(0);\r\n\r\n\treturn H*q2;\r\n}\r\n\r\n//Triad Algorithm for Finding attitude from two vectors\r\n// https://en.wikipedia.org/wiki/Triad_method\r\nMatrix Triad(Matrix V1_body, Matrix V2_body, Matrix V1_inertial, Matrix V2_inertial){\r\n\tMatrix R, r;\r\n\tMatrix r1, r2, r3, R1, R2, R3, V1_bodyNorm, V2_bodyNorm, V1_inertialNorm, V2_inertialNorm;\r\n\r\n\t//Normalize vectors and make them orthogonal\r\n\t// V1_bodyNorm = ScaleVec3(V1_body, 1.0 / p_normVec3(V1_body, 2));\r\n\t// V2_bodyNorm = ScaleVec3(V2_body, 1.0 / p_normVec3(V2_body, 2));\r\n\t// V1_inertialNorm = ScaleVec3(V1_inertial, 1.0 / p_normVec3(V1_inertial, 2));\r\n\t// V2_inertialNorm = ScaleVec3(V2_inertial, 1.0 / p_normVec3(V2_inertial, 2));\r\n\r\n\tV1_bodyNorm = V1_body * (1.0 / V1_body.norm());\r\n\tV2_bodyNorm = V2_body * (1.0 / V2_body.norm());\r\n\tV1_inertialNorm = V1_inertial * (1.0 / V1_inertial.norm());\r\n\tV2_inertialNorm = V2_inertial * (1.0 / V2_inertial.norm());\r\n\r\n\t//Set orthogonal vectors from body frame\r\n\tr1 = V1_bodyNorm; \r\n\tr2 = V1_bodyNorm.cross(V2_bodyNorm) * (1.0/V1_bodyNorm.cross(V2_bodyNorm).norm()); //(V1 x V2)/norm(V1 x V2)\r\n\tr3 = r1.cross(r2);\r\n\r\n\t//Set orthogonal vectors from inertial frame\r\n\tR1 = V1_inertialNorm;\r\n\tR2 = V1_inertialNorm.cross(V2_inertialNorm) * (1.0/V1_inertialNorm.cross(V2_inertialNorm).norm()); //(V1 x V2)/norm(V1 x V2)\r\n\tR3= R1.cross(R2);\r\n\r\n\t//We need to find the rotation matrix that solves [R1:R2:R3]=Rot.[r1:r2:r3]\r\n\t// ==> Rot = [R1:R2:R3].[r1:r2:r3]'\r\n\t// Matrix R = Concatenate3Vec3_2_Mat3x3(R1, R2, R3); //Creates matrix R = [R1:R2:R3]\r\n\tR << R1, R2, R3;\r\n\t//Matrix r = Concatenate3Vec3_2_Mat3x3(r1, r2, r3); //Creates matrix r = [r1:r2:r3]\r\n\tr << r1, r2, r3;\r\n\treturn R*r.transpose();\r\n}\r\n\r\n//Propagation quaternion for propagating quaternion with gyroscope data\r\n//Equation 34 in https://users.aalto.fi/~ssarkka/pub/quat.pdf\r\nMatrix propagationQuat(Matrix w, double dt){\r\n\tMatrix dq; //delta quaternion\r\n\tdouble norm_w = w.norm();\r\n\tdouble angle = dt*norm_w / 2;\r\n\tdouble sin_angle = sin(angle);\r\n\r\n\tdq(0,0) = cos(angle);\r\n\tif (norm_w != 0){\r\n\t\t// dq(1,0) << w(0) * sin_angle / norm_w,\r\n\t\t// dq(2,0) = w(1) * sin_angle / norm_w;\r\n\t\t// dq(3,0) = w(2) * sin_angle / norm_w;\r\n\t\tdq.tail(3) = w * (sin_angle / norm_w);\r\n\t}\r\n\telse{\r\n\t\tdq.tail(3) << 0,\r\n\t\t\t\t\t 0,\r\n\t\t\t\t\t 0;\r\n\t}\r\n\treturn dq;\r\n}\r\n\r\n//Propagate rotation matrix from initial point through angular velocity\r\n//Equation 33 in https://users.aalto.fi/~ssarkka/pub/quat.pdf, but instead of\r\n// using quaternion multiplication, we use rotation matrix multiplication\r\nMatrix propagateRotMat(Matrix M0, Matrix w, double dt){\r\n\tMatrix dq = propagationQuat(w, dt);\r\n\tMatrix dRot = Quat2rot(dq);\r\n\r\n\treturn M0*dRot;\r\n}", "meta": {"hexsha": "9ff37e606dd309946ce8fcbf004b2fe24748ddfd", "size": 6261, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "data/AGNC-Lab_Quad/multithreaded/control/QuatRotEuler.cpp", "max_stars_repo_name": "khairulislam/phys", "max_stars_repo_head_hexsha": "fc702520fcd3b23022b9253e7d94f878978b4500", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "data/AGNC-Lab_Quad/multithreaded/control/QuatRotEuler.cpp", "max_issues_repo_name": "khairulislam/phys", "max_issues_repo_head_hexsha": "fc702520fcd3b23022b9253e7d94f878978b4500", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data/AGNC-Lab_Quad/multithreaded/control/QuatRotEuler.cpp", "max_forks_repo_name": "khairulislam/phys", "max_forks_repo_head_hexsha": "fc702520fcd3b23022b9253e7d94f878978b4500", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1076923077, "max_line_length": 151, "alphanum_fraction": 0.5570995049, "num_tokens": 2540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129329, "lm_q2_score": 0.8519528000888387, "lm_q1q2_score": 0.7909604721975917}} {"text": "// normal_misc_examples.cpp\n\n// Copyright Paul A. Bristow 2007.\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Example of using normal distribution.\n\n// Note that this file contains Quickbook mark-up as well as code\n// and comments, don't change any of the special comment mark-ups!\n\n//[normal_basic1\n/*`\nFirst we need some includes to access the normal distribution\n(and some std output of course).\n*/\n\n#include // for normal_distribution\n using boost::math::normal; // typedef provides default type is double.\n\n#include \n using std::cout; using std::endl; using std::left; using std::showpoint; using std::noshowpoint;\n#include \n using std::setw; using std::setprecision;\n#include \n using std::numeric_limits;\n\nint main()\n{\n cout << \"Example: Normal distribution, Miscellaneous Applications.\";\n\n try\n {\n { // Traditional tables and values.\n/*`Let's start by printing some traditional tables.\n*/ \n double step = 1.; // in z \n double range = 4; // min and max z = -range to +range.\n int precision = 17; // traditional tables are only computed to much lower precision.\n\n // Construct a standard normal distribution s\n normal s; // (default mean = zero, and standard deviation = unity)\n cout << \"Standard normal distribution, mean = \"<< s.mean()\n << \", standard deviation = \" << s.standard_deviation() << endl;\n\n/*` First the probability distribution function (pdf).\n*/\n cout << \"Probability distribution function values\" << endl;\n cout << \" z \" \" pdf \" << endl;\n cout.precision(5);\n for (double z = -range; z < range + step; z += step)\n {\n cout << left << setprecision(3) << setw(6) << z << \" \" \n << setprecision(precision) << setw(12) << pdf(s, z) << endl;\n }\n cout.precision(6); // default\n /*`And the area under the normal curve from -[infin] up to z,\n the cumulative distribution function (cdf).\n*/\n // For a standard normal distribution \n cout << \"Standard normal mean = \"<< s.mean()\n << \", standard deviation = \" << s.standard_deviation() << endl;\n cout << \"Integral (area under the curve) from - infinity up to z \" << endl;\n cout << \" z \" \" cdf \" << endl;\n for (double z = -range; z < range + step; z += step)\n {\n cout << left << setprecision(3) << setw(6) << z << \" \" \n << setprecision(precision) << setw(12) << cdf(s, z) << endl;\n }\n cout.precision(6); // default\n\n/*`And all this you can do with a nanoscopic amount of work compared to\nthe team of *human computers* toiling with Milton Abramovitz and Irene Stegen\nat the US National Bureau of Standards (now [@http://www.nist.gov NIST]). \nStarting in 1938, their \"Handbook of Mathematical Functions with Formulas, Graphs and Mathematical Tables\",\nwas eventually published in 1964, and has been reprinted numerous times since.\n(A major replacement is planned at [@http://dlmf.nist.gov Digital Library of Mathematical Functions]).\n\nPretty-printing a traditional 2-dimensional table is left as an exercise for the student,\nbut why bother now that the Math Toolkit lets you write\n*/\n double z = 2.; \n cout << \"Area for z = \" << z << \" is \" << cdf(s, z) << endl; // to get the area for z.\n/*`\nCorrespondingly, we can obtain the traditional 'critical' values for significance levels.\nFor the 95% confidence level, the significance level usually called alpha,\nis 0.05 = 1 - 0.95 (for a one-sided test), so we can write\n*/\n cout << \"95% of area has a z below \" << quantile(s, 0.95) << endl;\n // 95% of area has a z below 1.64485\n/*`and a two-sided test (a comparison between two levels, rather than a one-sided test)\n\n*/\n cout << \"95% of area has a z between \" << quantile(s, 0.975)\n << \" and \" << -quantile(s, 0.975) << endl;\n // 95% of area has a z between 1.95996 and -1.95996\n/*`\n\nFirst, define a table of significance levels: these are the probabilities\nthat the true occurrence frequency lies outside the calculated interval.\n\nIt is convenient to have an alpha level for the probability that z lies outside just one standard deviation.\nThis will not be some nice neat number like 0.05, but we can easily calculate it,\n*/\n double alpha1 = cdf(s, -1) * 2; // 0.3173105078629142\n cout << setprecision(17) << \"Significance level for z == 1 is \" << alpha1 << endl;\n/*` \n and place in our array of favorite alpha values.\n*/\n double alpha[] = {0.3173105078629142, // z for 1 standard deviation.\n 0.20, 0.1, 0.05, 0.01, 0.001, 0.0001, 0.00001 };\n/*`\n\nConfidence value as % is (1 - alpha) * 100 (so alpha 0.05 == 95% confidence)\nthat the true occurrence frequency lies *inside* the calculated interval.\n\n*/\n cout << \"level of significance (alpha)\" << setprecision(4) << endl;\n cout << \"2-sided 1 -sided z(alpha) \" << endl;\n for (int i = 0; i < sizeof(alpha)/sizeof(alpha[0]); ++i)\n {\n cout << setw(15) << alpha[i] << setw(15) << alpha[i] /2 << setw(10) << quantile(complement(s, alpha[i]/2)) << endl;\n // Use quantile(complement(s, alpha[i]/2)) to avoid potential loss of accuracy from quantile(s, 1 - alpha[i]/2) \n }\n cout << endl;\n\n/*`Notice the distinction between one-sided (also called one-tailed)\nwhere we are using a > *or* < test (and not both)\nand considering the area of the tail (integral) from z up to +[infin],\nand a two-sided test where we are using two > *and* < tests, and thus considering two tails,\nfrom -[infin] up to z low and z high up to +[infin].\n\nSo the 2-sided values alpha[i] are calculated using alpha[i]/2.\n\nIf we consider a simple example of alpha = 0.05, then for a two-sided test,\nthe lower tail area from -[infin] up to -1.96 is 0.025 (alpha/2)\nand the upper tail area from +z up to +1.96 is also 0.025 (alpha/2),\nand the area between -1.96 up to 12.96 is alpha = 0.95.\nand the sum of the two tails is 0.025 + 0.025 = 0.05,\n\n*/\n//] [/[normal_basic1]\n\n//[normal_basic2\n\n/*`Armed with the cumulative distribution function, we can easily calculate the\neasy to remember proportion of values that lie within 1, 2 and 3 standard deviations from the mean.\n\n*/\n cout.precision(3);\n cout << showpoint << \"cdf(s, s.standard_deviation()) = \"\n << cdf(s, s.standard_deviation()) << endl; // from -infinity to 1 sd\n cout << \"cdf(complement(s, s.standard_deviation())) = \"\n << cdf(complement(s, s.standard_deviation())) << endl;\n cout << \"Fraction 1 standard deviation within either side of mean is \"\n << 1 - cdf(complement(s, s.standard_deviation())) * 2 << endl;\n cout << \"Fraction 2 standard deviations within either side of mean is \"\n << 1 - cdf(complement(s, 2 * s.standard_deviation())) * 2 << endl;\n cout << \"Fraction 3 standard deviations within either side of mean is \"\n << 1 - cdf(complement(s, 3 * s.standard_deviation())) * 2 << endl;\n\n/*`\nTo a useful precision, the 1, 2 & 3 percentages are 68, 95 and 99.7,\nand these are worth memorising as useful 'rules of thumb', as, for example, in\n[@http://en.wikipedia.org/wiki/Standard_deviation standard deviation]:\n\n[pre\nFraction 1 standard deviation within either side of mean is 0.683\nFraction 2 standard deviations within either side of mean is 0.954\nFraction 3 standard deviations within either side of mean is 0.997\n]\n\nWe could of course get some really accurate values for these\n[@http://en.wikipedia.org/wiki/Confidence_interval confidence intervals]\nby using cout.precision(15);\n\n[pre \nFraction 1 standard deviation within either side of mean is 0.682689492137086\nFraction 2 standard deviations within either side of mean is 0.954499736103642\nFraction 3 standard deviations within either side of mean is 0.997300203936740\n]\n\nBut before you get too excited about this impressive precision,\ndon't forget that the *confidence intervals of the standard deviation* are surprisingly wide,\nespecially if you have estimated the standard deviation from only a few measurements.\n*/\n//] [/[normal_basic2]\n\n\n//[normal_bulbs_example1\n/*`\nExamples from K. Krishnamoorthy, Handbook of Statistical Distributions with Applications,\nISBN 1 58488 635 8, page 125... implemented using the Math Toolkit library.\n\nA few very simple examples are shown here:\n*/\n// K. Krishnamoorthy, Handbook of Statistical Distributions with Applications,\n // ISBN 1 58488 635 8, page 125, example 10.3.5\n/*`Mean lifespan of 100 W bulbs is 1100 h with standard deviation of 100 h.\nAssuming, perhaps with little evidence and much faith, that the distribution is normal,\nwe construct a normal distribution called /bulbs/ with these values:\n*/\n double mean_life = 1100.;\n double life_standard_deviation = 100.;\n normal bulbs(mean_life, life_standard_deviation); \n double expected_life = 1000.;\n\n/*`The we can use the Cumulative distribution function to predict fractions\n(or percentages, if * 100) that will last various lifetimes.\n*/\n cout << \"Fraction of bulbs that will last at best (<=) \" // P(X <= 1000)\n << expected_life << \" is \"<< cdf(bulbs, expected_life) << endl;\n cout << \"Fraction of bulbs that will last at least (>) \" // P(X > 1000)\n << expected_life << \" is \"<< cdf(complement(bulbs, expected_life)) << endl;\n double min_life = 900;\n double max_life = 1200;\n cout << \"Fraction of bulbs that will last between \"\n << min_life << \" and \" << max_life << \" is \"\n << cdf(bulbs, max_life) // P(X <= 1200)\n - cdf(bulbs, min_life) << endl; // P(X <= 900) \n/*`\n[note Real-life failures are often very ab-normal,\nwith a significant number that 'dead-on-arrival' or suffer failure very early in their life:\nthe lifetime of the survivors of 'early mortality' may be well described by the normal distribution.]\n*/\n//] [/normal_bulbs_example1 Quickbook end]\n }\n { \n // K. Krishnamoorthy, Handbook of Statistical Distributions with Applications,\n // ISBN 1 58488 635 8, page 125, Example 10.3.6 \n\n//[normal_bulbs_example3\n/*`Weekly demand for 5 lb sacks of onions at a store is normally distributed with mean 140 sacks and standard deviation 10.\n*/\n double mean = 140.; // sacks per week.\n double standard_deviation = 10; \n normal sacks(mean, standard_deviation);\n\n double stock = 160.; // per week.\n cout << \"Percentage of weeks overstocked \"\n << cdf(sacks, stock) * 100. << endl; // P(X <=160)\n // Percentage of weeks overstocked 97.7\n\n/*`So there will be lots of mouldy onions!\nSo we should be able to say what stock level will meet demand 95% of the weeks.\n*/\n double stock_95 = quantile(sacks, 0.95);\n cout << \"Store should stock \" << int(stock_95) << \" sacks to meet 95% of demands.\" << endl;\n/*`And it is easy to estimate how to meet 80% of demand, and waste even less.\n*/\n double stock_80 = quantile(sacks, 0.80);\n cout << \"Store should stock \" << int(stock_80) << \" sacks to meet 8 out of 10 demands.\" << endl;\n//] [/normal_bulbs_example3 Quickbook end]\n }\n { // K. Krishnamoorthy, Handbook of Statistical Distributions with Applications,\n // ISBN 1 58488 635 8, page 125, Example 10.3.7 \n\n//[normal_bulbs_example4\n\n/*`A machine is set to pack 3 kg of ground beef per pack. \nOver a long period of time it is found that the average packed was 3 kg\nwith a standard deviation of 0.1 kg. \nAssuming the packing is normally distributed,\nwe can find the fraction (or %) of packages that weigh more than 3.1 kg.\n*/\n\ndouble mean = 3.; // kg\ndouble standard_deviation = 0.1; // kg\nnormal packs(mean, standard_deviation);\n\ndouble max_weight = 3.1; // kg\ncout << \"Percentage of packs > \" << max_weight << \" is \"\n<< cdf(complement(packs, max_weight)) << endl; // P(X > 3.1)\n\ndouble under_weight = 2.9;\ncout <<\"fraction of packs <= \" << under_weight << \" with a mean of \" << mean \n << \" is \" << cdf(complement(packs, under_weight)) << endl;\n// fraction of packs <= 2.9 with a mean of 3 is 0.841345\n// This is 0.84 - more than the target 0.95\n// Want 95% to be over this weight, so what should we set the mean weight to be?\n// KK StatCalc says:\ndouble over_mean = 3.0664;\nnormal xpacks(over_mean, standard_deviation);\ncout << \"fraction of packs >= \" << under_weight\n<< \" with a mean of \" << xpacks.mean() \n << \" is \" << cdf(complement(xpacks, under_weight)) << endl;\n// fraction of packs >= 2.9 with a mean of 3.06449 is 0.950005\ndouble under_fraction = 0.05; // so 95% are above the minimum weight mean - sd = 2.9\ndouble low_limit = standard_deviation;\ndouble offset = mean - low_limit - quantile(packs, under_fraction);\ndouble nominal_mean = mean + offset;\n\nnormal nominal_packs(nominal_mean, standard_deviation);\ncout << \"Setting the packer to \" << nominal_mean << \" will mean that \"\n << \"fraction of packs >= \" << under_weight \n << \" is \" << cdf(complement(nominal_packs, under_weight)) << endl;\n\n/*`\nSetting the packer to 3.06449 will mean that fraction of packs >= 2.9 is 0.95.\n\nSetting the packer to 3.13263 will mean that fraction of packs >= 2.9 is 0.99,\nbut will more than double the mean loss from 0.0644 to 0.133.\n\nAlternatively, we could invest in a better (more precise) packer with a lower standard deviation.\n\nTo estimate how much better (how much smaller standard deviation) it would have to be,\nwe need to get the 5% quantile to be located at the under_weight limit, 2.9\n*/\ndouble p = 0.05; // wanted p th quantile.\ncout << \"Quantile of \" << p << \" = \" << quantile(packs, p)\n << \", mean = \" << packs.mean() << \", sd = \" << packs.standard_deviation() << endl; // \n/*`\nQuantile of 0.05 = 2.83551, mean = 3, sd = 0.1\n\nWith the current packer (mean = 3, sd = 0.1), the 5% quantile is at 2.8551 kg,\na little below our target of 2.9 kg.\nSo we know that the standard deviation is going to have to be smaller.\n\nLet's start by guessing that it (now 0.1) needs to be halved, to a standard deviation of 0.05\n*/\nnormal pack05(mean, 0.05); \ncout << \"Quantile of \" << p << \" = \" << quantile(pack05, p) \n << \", mean = \" << pack05.mean() << \", sd = \" << pack05.standard_deviation() << endl;\n\ncout <<\"Fraction of packs >= \" << under_weight << \" with a mean of \" << mean \n << \" and standard deviation of \" << pack05.standard_deviation()\n << \" is \" << cdf(complement(pack05, under_weight)) << endl;\n// \n/*`\nFraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.05 is 0.9772\n\nSo 0.05 was quite a good guess, but we are a little over the 2.9 target,\nso the standard deviation could be a tiny bit more. So we could do some\nmore guessing to get closer, say by increasing to 0.06\n*/\n\nnormal pack06(mean, 0.06); \ncout << \"Quantile of \" << p << \" = \" << quantile(pack06, p) \n << \", mean = \" << pack06.mean() << \", sd = \" << pack06.standard_deviation() << endl;\n\ncout <<\"Fraction of packs >= \" << under_weight << \" with a mean of \" << mean \n << \" and standard deviation of \" << pack06.standard_deviation()\n << \" is \" << cdf(complement(pack06, under_weight)) << endl;\n/*`\nFraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.06 is 0.9522\n\nNow we are getting really close, but to do the job properly,\nwe could use root finding method, for example the tools provided, and used elsewhere,\nin the Math Toolkit, see\n[link math_toolkit.toolkit.internals1.roots2 Root Finding Without Derivatives].\n\nBut in this normal distribution case, we could be even smarter and make a direct calculation.\n*/\n\nnormal s; // For standard normal distribution, \ndouble sd = 0.1;\ndouble x = 2.9; // Our required limit.\n// then probability p = N((x - mean) / sd)\n// So if we want to find the standard deviation that would be required to meet this limit,\n// so that the p th quantile is located at x,\n// in this case the 0.95 (95%) quantile at 2.9 kg pack weight, when the mean is 3 kg.\n\ndouble prob = pdf(s, (x - mean) / sd);\ndouble qp = quantile(s, 0.95);\ncout << \"prob = \" << prob << \", quantile(p) \" << qp << endl; // p = 0.241971, quantile(p) 1.64485\n// Rearranging, we can directly calculate the required standard deviation:\ndouble sd95 = abs((x - mean)) / qp;\n\ncout << \"If we want the \"<< p << \" th quantile to be located at \" \n << x << \", would need a standard deviation of \" << sd95 << endl;\n\nnormal pack95(mean, sd95); // Distribution of the 'ideal better' packer.\ncout <<\"Fraction of packs >= \" << under_weight << \" with a mean of \" << mean \n << \" and standard deviation of \" << pack95.standard_deviation()\n << \" is \" << cdf(complement(pack95, under_weight)) << endl;\n\n// Fraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.0608 is 0.95\n\n/*`Notice that these two deceptively simple questions\n(do we over-fill or measure better) are actually very common.\nThe weight of beef might be replaced by a measurement of more or less anything.\nBut the calculations rely on the accuracy of the standard deviation - something\nthat is almost always less good than we might wish,\nespecially if based on a few measurements.\n*/\n\n//] [/normal_bulbs_example4 Quickbook end]\n }\n\n { // K. Krishnamoorthy, Handbook of Statistical Distributions with Applications,\n // ISBN 1 58488 635 8, page 125, example 10.3.8\n//[normal_bulbs_example5\n/*`A bolt is usable if between 3.9 and 4.1 long.\nFrom a large batch of bolts, a sample of 50 show a \nmean length of 3.95 with standard deviation 0.1.\nAssuming a normal distribution, what proportion is usable?\nThe true sample mean is unknown, \nbut we can use the sample mean and standard deviation to find approximate solutions.\n*/\n\n normal bolts(3.95, 0.1);\n double top = 4.1;\n double bottom = 3.9; \n\ncout << \"Fraction long enough [ P(X <= \" << top << \") ] is \" << cdf(bolts, top) << endl;\ncout << \"Fraction too short [ P(X <= \" << bottom << \") ] is \" << cdf(bolts, bottom) << endl;\ncout << \"Fraction OK -between \" << bottom << \" and \" << top\n << \"[ P(X <= \" << top << \") - P(X<= \" << bottom << \" ) ] is \"\n << cdf(bolts, top) - cdf(bolts, bottom) << endl;\n\ncout << \"Fraction too long [ P(X > \" << top << \") ] is \"\n << cdf(complement(bolts, top)) << endl;\n\ncout << \"95% of bolts are shorter than \" << quantile(bolts, 0.95) << endl;\n \n//] [/normal_bulbs_example5 Quickbook end]\n }\n }\n catch(const std::exception& e)\n { // Always useful to include try & catch blocks because default policies \n // are to throw exceptions on arguments that cause errors like underflow, overflow. \n // Lacking try & catch blocks, the program will abort without a message below,\n // which may give some helpful clues as to the cause of the exception.\n std::cout <<\n \"\\n\"\"Message from thrown exception was:\\n \" << e.what() << std::endl;\n }\n return 0;\n} // int main()\n\n\n/*\n\nOutput is:\n\nAutorun \"i:\\boost-06-05-03-1300\\libs\\math\\test\\Math_test\\debug\\normal_misc_examples.exe\"\nExample: Normal distribution, Miscellaneous Applications.Standard normal distribution, mean = 0, standard deviation = 1\nProbability distribution function values\n z pdf \n-4 0.00013383022576488537\n-3 0.0044318484119380075\n-2 0.053990966513188063\n-1 0.24197072451914337\n0 0.3989422804014327\n1 0.24197072451914337\n2 0.053990966513188063\n3 0.0044318484119380075\n4 0.00013383022576488537\nStandard normal mean = 0, standard deviation = 1\nIntegral (area under the curve) from - infinity up to z \n z cdf \n-4 3.1671241833119979e-005\n-3 0.0013498980316300959\n-2 0.022750131948179219\n-1 0.1586552539314571\n0 0.5 \n1 0.84134474606854293\n2 0.97724986805182079\n3 0.9986501019683699\n4 0.99996832875816688\nArea for z = 2 is 0.97725\n95% of area has a z below 1.64485\n95% of area has a z between 1.95996 and -1.95996\nSignificance level for z == 1 is 0.3173105078629142\nlevel of significance (alpha)\n2-sided 1 -sided z(alpha) \n0.3173 0.1587 1 \n0.2 0.1 1.282 \n0.1 0.05 1.645 \n0.05 0.025 1.96 \n0.01 0.005 2.576 \n0.001 0.0005 3.291 \n0.0001 5e-005 3.891 \n1e-005 5e-006 4.417 \ncdf(s, s.standard_deviation()) = 0.841\ncdf(complement(s, s.standard_deviation())) = 0.159\nFraction 1 standard deviation within either side of mean is 0.683\nFraction 2 standard deviations within either side of mean is 0.954\nFraction 3 standard deviations within either side of mean is 0.997\nFraction of bulbs that will last at best (<=) 1.00e+003 is 0.159\nFraction of bulbs that will last at least (>) 1.00e+003 is 0.841\nFraction of bulbs that will last between 900. and 1.20e+003 is 0.819\nPercentage of weeks overstocked 97.7\nStore should stock 156 sacks to meet 95% of demands.\nStore should stock 148 sacks to meet 8 out of 10 demands.\nPercentage of packs > 3.10 is 0.159\nfraction of packs <= 2.90 with a mean of 3.00 is 0.841\nfraction of packs >= 2.90 with a mean of 3.07 is 0.952\nSetting the packer to 3.06 will mean that fraction of packs >= 2.90 is 0.950\nQuantile of 0.0500 = 2.84, mean = 3.00, sd = 0.100\nQuantile of 0.0500 = 2.92, mean = 3.00, sd = 0.0500\nFraction of packs >= 2.90 with a mean of 3.00 and standard deviation of 0.0500 is 0.977\nQuantile of 0.0500 = 2.90, mean = 3.00, sd = 0.0600\nFraction of packs >= 2.90 with a mean of 3.00 and standard deviation of 0.0600 is 0.952\nprob = 0.242, quantile(p) 1.64\nIf we want the 0.0500 th quantile to be located at 2.90, would need a standard deviation of 0.0608\nFraction of packs >= 2.90 with a mean of 3.00 and standard deviation of 0.0608 is 0.950\nFraction long enough [ P(X <= 4.10) ] is 0.933\nFraction too short [ P(X <= 3.90) ] is 0.309\nFraction OK -between 3.90 and 4.10[ P(X <= 4.10) - P(X<= 3.90 ) ] is 0.625\nFraction too long [ P(X > 4.10) ] is 0.0668\n95% of bolts are shorter than 4.11\n\n*/\n\n\n\n", "meta": {"hexsha": "f57707cfec82cc46cb24e76a9283ac353e623c13", "size": 21779, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/normal_misc_examples.cpp", "max_stars_repo_name": "bittorrent/boost_1_44_0", "max_stars_repo_head_hexsha": "81d5bca204ceb8448867e46cd96c1c8697599066", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T23:20:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T19:38:34.000Z", "max_issues_repo_path": "libs/math/example/normal_misc_examples.cpp", "max_issues_repo_name": "jonstewart/boost-svn", "max_issues_repo_head_hexsha": "7f6dc0c0cb807b28072c7bdd3d77bb01ab290c59", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/example/normal_misc_examples.cpp", "max_forks_repo_name": "jonstewart/boost-svn", "max_forks_repo_head_hexsha": "7f6dc0c0cb807b28072c7bdd3d77bb01ab290c59", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-07-26T08:07:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-25T23:20:21.000Z", "avg_line_length": 42.7039215686, "max_line_length": 123, "alphanum_fraction": 0.6739978879, "num_tokens": 6326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225517, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.790862693657578}} {"text": "/**\n * @file gaussian.hpp\n * @author Vahid Bastani\n *\n * Multivariate Gaussian distribution\n */\n#ifndef SSMPACK_DISTRIBUTION_GAUSSIAN_HPP\n#define SSMPACK_DISTRIBUTION_GAUSSIAN_HPP\n\n#include \"ssmkit/random/generator.hpp\"\n\n#include \n\n#include \n\nnamespace ssmkit {\nnamespace distribution {\n\n/** A D-dimensional multivariate Gaussian distribution.\n * \\f[ \\mathcal{N}(\\mathbf{x}| \\mu, \\Sigma) = \n * \\frac{1}{(2\\pi)^{D/2}\\sqrt{|\\Sigma|}}\n * \\exp(-\\frac{1}{2}\\mathbf{x}^T\\Sigma^{-1}\\mathbf{x})\\f]\n */\nclass Gaussian {\n\n public:\n //! Data type of the parameter variable \\f$ \\theta = \\{\\mu, \\Sigma\\} \\f$.\n using TParameterVAR = std::tuple;\n\n private:\n //! mean vector \\f$\\mu\\f$.\n arma::vec mean_;\n //! covariance matrix \\f$\\Sigma\\f$.\n arma::mat covariance_;\n /** a normal distribution random generator \\f$\\mathcal{N}(0,1)\\f$ */\n std::normal_distribution normal_;\n //! \\f$\\pi\\f$\n static constexpr double pi = 3.1415926535897;\n //! inverse of covariance matrix \\f$\\Sigma^{-1}\\f$.\n arma::mat inv_cov_;\n //! partitioning function \\f$\\frac{1}{(2\\pi)^{D/2}\\sqrt{|\\Sigma|}}\\f$.\n double part_;\n //! Cholesky decomposition of covariance matrix, i.e. \\f$L\\f$ such that \\f$LL^T=\\Sigma\\f$.\n arma::mat chol_dec_;\n //! Dimension \\f$D\\f$\n int dim_;\n\n private:\n /**\n * Calculates useful constant values for avoiding recalculation for every \n * call to likelihood().\n */\n void calcDistConstants() {\n dim_ = mean_.n_rows;\n inv_cov_ = arma::inv(covariance_);\n // calculate partition function\n double det_cov = arma::det(covariance_);\n double den_pi = 1 / std::sqrt(std::pow(2 * pi, dim_));\n part_ = den_pi * (1 / std::sqrt(det_cov));\n // Cholesky decomposition\n chol_dec_ = arma::chol(covariance_, \"lower\");\n }\n\n public:\n Gaussian() = delete;\n /** Default constructor.\n * Returns D dimensional Gaussian distribution with zero mean and identity\n * covariance matrix.\n */\n Gaussian(int dim) : Gaussian(arma::zeros(dim), arma::eye(dim, dim)) {}\n \n /**\n * Returns D dimensional Gaussian with given mean and covariance. The\n * covariance should be positive definite.\n * \n * @param mean The mean vector.\n * @param covariance The covariance matrix.\n */\n Gaussian(arma::vec mean, arma::mat covariance)\n : mean_(std::move(mean)), covariance_(std::move(covariance)) {\n calcDistConstants();\n }\n\n /** Returns a random variable from the distribution.\n * \\f[ \\mathbf{x} \\sim \\mathcal{N}(\\mu, \\Sigma) \\f]\n * @return The random vector \\f$\\mathbf{x}\\f$\n */\n arma::vec random() {\n arma::vec rnd(dim_); // how much overload the vector construction has?\n rnd.imbue(\n [&]() { return normal_(random::Generator::get().getGenerator()); });\n return mean_ + chol_dec_ * rnd;\n }\n\n /** Returns the likelihood of a given random variable.\n * \\f[p(\\mathbf{x}) = \\frac{1}{(2\\pi)^{D/2}\\sqrt{|\\Sigma|}}\n * \\exp(-\\frac{1}{2}\\mathbf{x}^T\\Sigma^{-1}\\mathbf{x})\\f]\n * @param rv The random variable \\f$\\mathbf{x}\\f$ for which likelihood is calculated.\n * @return \\f$p(\\mathbf{x})\\f$.\n */\n double likelihood(const arma::vec &rv) const {\n const auto diff = rv - mean_;\n const arma::vec tmp = diff.t() * inv_cov_ * diff;\n const double expt = -tmp(0) / 2;\n return part_ * std::exp(expt);\n }\n\n /** Changes the mean and covariance of the distribution with the given\n * parameters.\n * @param parameters A tuple containing mean and covariance.\n * @return Reference to the current instance.\n */\n Gaussian ¶meterize(const TParameterVAR ¶meters) {\n return parameterize(std::get<0>(parameters), std::get<1>(parameters));\n }\n\n /** Changes the mean and covariance of the distribution with the given values.\n * @param mean The mean vector.\n * @param covariance The covariance matrix.\n * @return Reference to the current instance.\n */\n Gaussian ¶meterize(const arma::vec &mean,\n const arma::mat &covariance) {\n mean_ = mean;\n covariance_ = covariance;\n calcDistConstants();\n return (*this);\n }\n //! Returns the mean vector \n const arma::vec& getMean() const { return mean_; }\n //! Returns the covariance matrix\n const arma::mat& getCovariance() const { return covariance_; }\n};\n\n} // namespace distribution\n} // namespace ssmkit\n\n#endif // SSMPACK_DISTRIBUTION_GAUSSIAN_HPP\n", "meta": {"hexsha": "e1cc12d8bdc8842d4e3c96ccfb59b95c60248c9b", "size": 4351, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ssmkit/distribution/gaussian.hpp", "max_stars_repo_name": "vahid-bastani/ssmpack", "max_stars_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-07-08T09:18:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-10T06:46:55.000Z", "max_issues_repo_path": "src/ssmkit/distribution/gaussian.hpp", "max_issues_repo_name": "vahidbas/ssmkit", "max_issues_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ssmkit/distribution/gaussian.hpp", "max_forks_repo_name": "vahidbas/ssmkit", "max_forks_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-01-03T17:46:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-03T17:46:08.000Z", "avg_line_length": 31.3021582734, "max_line_length": 93, "alphanum_fraction": 0.6527235118, "num_tokens": 1222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.790861382793586}} {"text": "/**\n * @file initcondlv_main.cc\n * @brief NPDE homework InitCondLV code\n * @author lfilippo, tille, jgacon, dcasati\n * @copyright Developed at ETH Zurich\n */\n\n#include \n#include \n#include \n\n#include \"initcondlv.h\"\n\nint main() {\n /* Compute initial conditions u0, v0 such that solution has period T=5\n * using inital approximation [3,2]^T */\n /* SAM_LISTING_BEGIN_2 */\n Eigen::Vector2d y(3, 2); // Initial guess\n double T = 25; // Period\n\n Eigen::Vector2d F;\n\n while(true) {\n\tauto [phi, W] = InitCondLV::PhiAndW(y[0], y[1], T);\n\n\tF = phi - y;\n\tEigen::Matrix2d DF = W - Eigen::Matrix2d::Identity();\n\n\tif(F.norm() > 1e-10) {\n\t\ty -= DF.lu().solve(F);\n\t} else {\n\t\tbreak;\n\t}\n\n }\n\n // Calculate the evolution of the Lotka-Volterra ODE up to\n // time 100, using the initial value y, found by the Newton iterations above.\n // If the evolution is indeed 5-periodic, then the solution at time 100\n // should have the value y. Print a warning message if this is not the case.\n //====================\n // Your code goes here\n //====================\n\n\n std::cout << y << std::endl;\n\n // Testing obtained solution against reference \"exact\" solution\n Eigen::Vector2d ref(3.1098751029156, 2.08097564048345);\n double tol = 1.0e-8;\n double error = (ref - y).lpNorm();\n if (std::abs(error) > tol) {\n std::cout\n << \" Error w.r.t. to reference solution is GREATER than tol=1.0e-8.\"\n << std::endl;\n } else {\n std::cout\n << \" Error w.r.t. to reference solution is SMALLER than tol=1.0e-8.\"\n << std::endl;\n }\n\n /* SAM_LISTING_END_2 */\n return 0;\n}\n", "meta": {"hexsha": "c60dc485e9c1b0ebc5fd6f2f6345ace323dc582f", "size": 1645, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/InitCondLV/mysolution/initcondlv_main.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/InitCondLV/mysolution/initcondlv_main.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/InitCondLV/mysolution/initcondlv_main.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3076923077, "max_line_length": 79, "alphanum_fraction": 0.6151975684, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811306, "lm_q2_score": 0.8688267677469952, "lm_q1q2_score": 0.7905515651289984}} {"text": "// TestPI.cpp\n//\n// Calculation of PI using random numbers; it's analogous\n// to throwing darts.\n//\n// (C) Datasim Education BV 2010-2011\n//\n\n#include // Convenience header file\n#include \n#include \t\t\t// std::time\nusing namespace std;\n\n#include \n\nint main()\n{\n\t// A. Define the lagged Fibonacci and Normal objects\n\tboost::lagged_fibonacci607 rng;\n\trng.seed(static_cast (std::time(0)));\n\tboost::uniform_real<> uni(0.0,1.0);\n\n\t// B. Produce Uniform (0, 1)\n\tboost::variate_generator > \n\t\t\t\t\t\t\tuniRng(rng, uni);\n\n\t// C. Choose the desired accuracy\n\tcout << \"How many darts to throw? \"; long N; cin >> N;\n\n\t// D. Thow the dart; does it fall in the circle or outside\n\t// Start throwing darts and count where they land\n\tlong hits = 0;\n\tdouble x, y, distance;\n\tfor (long n = 1; n <= N; ++n)\n\t{\n\t\tx = uniRng(); y = uniRng();\n\t\tdistance = sqrt(x*x + y*y);\n\n\t\tif ( distance <=1)\n\t\t{\n\t\t\thits++;\n\t\t}\n\t}\n\n\t//E. Produce the answer\n\tcout << \"Numbers of hits, PI is: \" << hits << \", \" << 4.0 * double(hits) / double (N) << endl;\n\t\t\n\treturn 0;\n\n}int outcome; ", "meta": {"hexsha": "377dd8e835ef4d1b1557d56327e7fb59f78bac49", "size": 1163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Level_8/V. An Introduction to the Boost C++ Libraries/04b - Random - PI calculation/TestPI.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_8/V. An Introduction to the Boost C++ Libraries/04b - Random - PI calculation/TestPI.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_8/V. An Introduction to the Boost C++ Libraries/04b - Random - PI calculation/TestPI.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": 23.26, "max_line_length": 95, "alphanum_fraction": 0.6380051591, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422255326288, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7905352442976981}} {"text": "\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// Copyright Paul A. Bristow 2015.\r\n// Copyright Christopher Kormanyos 2015.\r\n\r\n// This file is written to be included from a Quickbook .qbk document.\r\n// It can be compiled by the C++ compiler, and run. Any output can\r\n// also be added here as comment or included or pasted in elsewhere.\r\n// Caution: this file contains Quickbook markup as well as code\r\n// and comments: don't change any of the special comment markups!\r\n\r\n// This file also includes Doxygen-style documentation about the function of the code.\r\n// See http://www.doxygen.org for details.\r\n\r\n//! \\file\r\n\r\n//! \\brief Example program showing a polynomial approximation of cos(negatable).\r\n\r\n// Below are snippets of code that are included into Quickbook file fixed_point.qbk.\r\n\r\n#include \r\n#include \r\n\r\n#include \r\n\r\nnamespace local\r\n{\r\n template\r\n NumericType cos(const NumericType& x)\r\n {\r\n // This subroutine computes cos(x) using a beautiful\r\n // approximation obtained by Laguerre in 1880 which\r\n // achieves about 3-4 decimal digits of precision\r\n // in the range 0 < x < +pi/2.\r\n\r\n // See J. F. Hart et al., Computer Approximations\r\n // (John Wiley and Sons, Inc., 1968), Eq. 2.4.4\r\n // in Sect. 2.4 on page 27.\r\n // In other words:\r\n // cos(pi x/2) = 1 - chi^2 / {chi - (chi - 1) sqrt[(2 - chi) / 3]},\r\n // where a scaled argument chi is used with\r\n // chi = x / (pi/2).\r\n\r\n const NumericType chi = (x * 2) / NumericType(3.14159265358979323846F);\r\n\r\n return 1 - ((chi * chi) / (chi - ((chi - 1) * sqrt((2 - chi) / 3))));\r\n }\r\n}\r\n\r\nint main()\r\n{\r\n // This example computes approximations of cos(x) in the\r\n // range 0 < x < pi/2. Comparison are made between\r\n // fixed-point calculations and floating-point calculations.\r\n // A 16-bit fixed-point type is used, as may be well-suited\r\n // for a tiny bare-metal embedded system.\r\n\r\n // The arguments used in the comparisons are:\r\n // x = (approx.) 1/4, 1/2, 3/4, 1, 5/4, 3/2.\r\n\r\n // Here we compute cos(n/4) for 1 <= n < 7 for\r\n // a fixed-point negatable type.\r\n std::cout << \"fixed-point: \";\r\n for(int n = 1; n < 7; ++n)\r\n {\r\n typedef boost::fixed_point::negatable<4, -11> fixed_point_type;\r\n\r\n const fixed_point_type x = fixed_point_type(n) / 4;\r\n\r\n std::cout << std::setprecision(4)\r\n << std::fixed\r\n << local::cos(x)\r\n << \" \";\r\n }\r\n std::cout << std::endl;\r\n\r\n // Compare with the control values of cos(n/4)\r\n // computed with a built-in floating-point type.\r\n std::cout << \"float-point: \";\r\n for(int n = 1; n < 7; ++n)\r\n {\r\n using std::cos;\r\n\r\n const float x = float(n) / 4;\r\n\r\n std::cout << std::setprecision(4)\r\n << std::fixed\r\n << cos(x)\r\n << \" \";\r\n }\r\n std::cout << std::endl;\r\n}\r\n", "meta": {"hexsha": "6208c468c5558f2e30983f4edd635bc53d004088", "size": 3051, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fixed_point_laguerre_approx_cos.cpp", "max_stars_repo_name": "BoostGSoC15/fixed-point", "max_stars_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/fixed_point_laguerre_approx_cos.cpp", "max_issues_repo_name": "BoostGSoC15/fixed-point", "max_issues_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/fixed_point_laguerre_approx_cos.cpp", "max_forks_repo_name": "BoostGSoC15/fixed-point", "max_forks_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4536082474, "max_line_length": 87, "alphanum_fraction": 0.6135693215, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.789984124071508}} {"text": "/* a zero-sum game example\n payoff matrix\n 4 1 8\n 2 3 1\n 0 4 3\n player's optimal strategy\n I's (.25,.75,0)\n II's (.5,.5,0)\n Nash equilibrium value 5/2\n \n Another zero-sum game example\n payoff matrix\n 2 3 1 5\n 4 1 6 0\n player's optimal strategy\n I's (0.7143,0.2857)\n II's (0,0.7143,0.2857,0)\n Nash equilibrium value 2.42857\n*/\n\n#include \n#include \"zeroSumGame.h\"\n\nusing namespace arma;\nusing namespace std;\n\nint main()\n{\n// Mat payoffMat(3,3);\n// payoffMat << 4 << 1 << 8 << endr\n// << 2 << 3 << 1 << endr\n// << 0 << 4 << 3 << endr;\n \n Mat payoffMat(2,4);\n payoffMat << 2 << 3 << 1 << 5 << endr\n << 4 << 1 << 6 << 0 << endr;\n \n double gameValue = 0;\n //Col p(payoffMat.n_rows);\n //p.fill(0.0);\n //Col q(payoffMat.n_cols);\n //q.fill(0.0);\n Col p;\n Col q;\n double equilibriumThreshold = 1e-4;\n bool checkNonnegative = true;\n \n double maxAbsValue = max(max(abs(payoffMat)));\n Mat normPayoffMat = payoffMat/maxAbsValue+1.0;\n if(ZeroSumGame::solveGame(normPayoffMat,gameValue,p,q,equilibriumThreshold,checkNonnegative)){\n gameValue = (gameValue-1)*maxAbsValue;\n cout << gameValue << endl;\n p.print(\"p:\");\n q.print(\"q:\");\n }\n return 0;\n}", "meta": {"hexsha": "c99d042edb67102baff470614c76d404f1440309", "size": 1309, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gurobi_C++/src/test_.cpp", "max_stars_repo_name": "xiangli-chen/two-person-zero-sum-game", "max_stars_repo_head_hexsha": "53e9a7a53009d9483b31d96cb0171d57819676fd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gurobi_C++/src/test_.cpp", "max_issues_repo_name": "xiangli-chen/two-person-zero-sum-game", "max_issues_repo_head_hexsha": "53e9a7a53009d9483b31d96cb0171d57819676fd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gurobi_C++/src/test_.cpp", "max_forks_repo_name": "xiangli-chen/two-person-zero-sum-game", "max_forks_repo_head_hexsha": "53e9a7a53009d9483b31d96cb0171d57819676fd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9649122807, "max_line_length": 98, "alphanum_fraction": 0.5889992361, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.8633916222765627, "lm_q1q2_score": 0.7899178257638134}} {"text": "/* =========================================================================\n Copyright (c) 2010-2014, Institute for Microelectronics,\n Institute for Analysis and Scientific Computing,\n TU Wien.\n Portions of this software are copyright by UChicago Argonne, LLC.\n\n -----------------\n ViennaCL - The Vienna Computing Library\n -----------------\n\n Project Head: Karl Rupp rupp@iue.tuwien.ac.at\n\n (A list of authors and contributors can be found in the PDF manual)\n\n License: MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n/*\n*\n* Tutorial: Least Squares problem for matrices from ViennaCL or Boost.uBLAS (least-squares.cpp and least-squares.cu are identical, the latter being required for compilation using CUDA nvcc)\n*\n* See Example 2 at http://tutorial.math.lamar.edu/Classes/LinAlg/QRDecomposition.aspx for a reference solution.\n*\n*/\n\n// activate ublas support in ViennaCL\n#define VIENNACL_WITH_UBLAS\n\n//\n// include necessary system headers\n//\n#include \n\n//\n// Boost includes\n//\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n//\n// ViennaCL includes\n//\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/matrix.hpp\"\n#include \"viennacl/matrix_proxy.hpp\"\n#include \"viennacl/linalg/qr.hpp\"\n#include \"viennacl/linalg/lu.hpp\"\n\n\n/*\n* Tutorial: Least Squares problem for matrices from ViennaCL or Boost.uBLAS\n*\n* See Example 2 at http://tutorial.math.lamar.edu/Classes/LinAlg/QRDecomposition.aspx for a reference solution.\n*/\n\nint main (int, const char **)\n{\n typedef float ScalarType; //feel free to change this to 'double' if supported by your hardware\n typedef boost::numeric::ublas::matrix MatrixType;\n typedef boost::numeric::ublas::vector VectorType;\n typedef viennacl::matrix VCLMatrixType;\n typedef viennacl::vector VCLVectorType;\n\n //\n // Create vectors and matrices with data, cf. http://tutorial.math.lamar.edu/Classes/LinAlg/QRDecomposition.aspx\n //\n VectorType ublas_b(4);\n ublas_b(0) = -4;\n ublas_b(1) = 2;\n ublas_b(2) = 5;\n ublas_b(3) = -1;\n\n MatrixType ublas_A(4, 3);\n MatrixType Q = boost::numeric::ublas::zero_matrix(4, 4);\n MatrixType R = boost::numeric::ublas::zero_matrix(4, 3);\n\n ublas_A(0, 0) = 2; ublas_A(0, 1) = -1; ublas_A(0, 2) = 1;\n ublas_A(1, 0) = 1; ublas_A(1, 1) = -5; ublas_A(1, 2) = 2;\n ublas_A(2, 0) = -3; ublas_A(2, 1) = 1; ublas_A(2, 2) = -4;\n ublas_A(3, 0) = 1; ublas_A(3, 1) = -1; ublas_A(3, 2) = 1;\n\n //\n // Setup the matrix in ViennaCL:\n //\n VCLVectorType vcl_b(ublas_b.size());\n VCLMatrixType vcl_A(ublas_A.size1(), ublas_A.size2());\n\n viennacl::copy(ublas_b, vcl_b);\n viennacl::copy(ublas_A, vcl_A);\n\n\n\n //////////// Part 1: Use Boost.uBLAS for all computations ////////////////\n\n std::cout << \"--- Boost.uBLAS ---\" << std::endl;\n std::vector ublas_betas = viennacl::linalg::inplace_qr(ublas_A); //computes the QR factorization\n\n // compute modified RHS of the minimization problem:\n // b' := Q^T b\n viennacl::linalg::inplace_qr_apply_trans_Q(ublas_A, ublas_betas, ublas_b);\n\n // Final step: triangular solve: Rx = b'', where b'' are the first three entries in b'\n // We only need the upper left square part of A, which defines the upper triangular matrix R\n boost::numeric::ublas::range ublas_range(0, 3);\n boost::numeric::ublas::matrix_range ublas_R(ublas_A, ublas_range, ublas_range);\n boost::numeric::ublas::vector_range ublas_b2(ublas_b, ublas_range);\n boost::numeric::ublas::inplace_solve(ublas_R, ublas_b2, boost::numeric::ublas::upper_tag());\n\n std::cout << \"Result: \" << ublas_b2 << std::endl;\n\n //////////// Part 2: Use ViennaCL types for BLAS 3 computations, but use Boost.uBLAS for the panel factorization ////////////////\n\n std::cout << \"--- ViennaCL (hybrid implementation) ---\" << std::endl;\n std::vector hybrid_betas = viennacl::linalg::inplace_qr(vcl_A);\n\n // compute modified RHS of the minimization problem:\n // b := Q^T b\n viennacl::linalg::inplace_qr_apply_trans_Q(vcl_A, hybrid_betas, vcl_b);\n\n // Final step: triangular solve: Rx = b'.\n // We only need the upper part of A such that R is a square matrix\n viennacl::range vcl_range(0, 3);\n viennacl::matrix_range vcl_R(vcl_A, vcl_range, vcl_range);\n viennacl::vector_range vcl_b2(vcl_b, vcl_range);\n viennacl::linalg::inplace_solve(vcl_R, vcl_b2, viennacl::linalg::upper_tag());\n\n std::cout << \"Result: \" << vcl_b2 << std::endl;\n\n\n\n //\n // That's it.\n //\n std::cout << \"!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!\" << std::endl;\n\n return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "9216a96cdf5af3b9d3c65943f4ce4824d3e68f26", "size": 5197, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/least-squares.cpp", "max_stars_repo_name": "denis14/ViennaCL-1.5.2", "max_stars_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/tutorial/least-squares.cpp", "max_issues_repo_name": "denis14/ViennaCL-1.5.2", "max_issues_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/tutorial/least-squares.cpp", "max_forks_repo_name": "denis14/ViennaCL-1.5.2", "max_forks_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8413793103, "max_line_length": 191, "alphanum_fraction": 0.646142005, "num_tokens": 1521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7897368530128908}} {"text": "#include \n#include \n\n#include \n// 稠密矩阵的代数运算(逆、特征值等)\n#include \n\nusing namespace std;\n\n#define MATRIX_SIZE 50\n\nint main() {\n // define\n Eigen::Matrix matrix_23;\n Eigen::Vector3d v_3d;\n Eigen::Matrix3d matrix_33 = Eigen::Matrix3d::Zero();\n Eigen::Matrix matrix_dynamic;\n Eigen::MatrixXd matrix_x;\n\n // output\n cout << \"output ...\" << endl;\n matrix_23 << 1, 2, 3, 4, 5, 6;\n cout << matrix_23 << endl;\n\n // access\n cout << \"access ...\" << endl;\n for (int i = 0; i < 1; ++i) {\n for (int j = 0; j < 2; ++j) {\n cout << matrix_23(i, j) << endl;\n }\n }\n\n // vector * matrix\n cout << \"vector * matrix ...\" << endl;\n v_3d << 3, 2, 1;\n // 不能混用不同类型的矩阵,应该转换,并且维度要正确\n Eigen::Matrix result = matrix_23.cast() * v_3d;\n cout << result << endl;\n\n // matrix operation ...\n cout << \"matrix operation ...\" << endl;\n matrix_33 = Eigen::Matrix3d::Random();\n cout << matrix_33 << endl;\n cout << \"transponse: \\n\" << matrix_33.transpose() << endl;\n cout << \"sum: \\n\" << matrix_33.sum() << endl;\n cout << \"trace: \\n\" << matrix_33.trace() << endl;\n cout << \"times: \\n\" << 10 * matrix_33 << endl;\n cout << \"inverse: \\n\" << matrix_33.inverse() << endl;\n cout << \"determinant: \\n\" << matrix_33.determinant() << endl;\n\n // eigen value\n Eigen::SelfAdjointEigenSolver eigenSolver(matrix_33.transpose() * matrix_33);\n cout << \"eigen value: \\n\" << eigenSolver.eigenvalues() << endl;\n cout << \"eigen vectors: \\n\" << eigenSolver.eigenvectors() << endl;\n\n // solve: matrix_NN * x = v_Nd:直接求逆与矩形分解计算\n Eigen::Matrix matrix_NN = Eigen::MatrixXd::Random(MATRIX_SIZE, MATRIX_SIZE);\n Eigen::Matrix v_Nd = Eigen::MatrixXd::Random(MATRIX_SIZE, 1);\n\n clock_t time_start = clock();\n Eigen::Matrix x = matrix_NN.inverse() * v_Nd;\n cout << \"time use in normal inverse is \" << 1000 * (clock() - time_start) / static_cast(CLOCKS_PER_SEC)\n << \" ms\" << endl;\n\n time_start = clock();\n x = matrix_NN.colPivHouseholderQr().solve(v_Nd);\n cout << \"time use in QR composition is \" << 1000 * (clock() - time_start) / static_cast(CLOCKS_PER_SEC)\n << \" ms\" << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "33982a7a209841fb8b8c77f05ab099aca31dbfe7", "size": 2418, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Eg01_UseEigen/main.cpp", "max_stars_repo_name": "chengfzy/SLAM", "max_stars_repo_head_hexsha": "9ea4557d3df6ca9c9552d2b38a3c663241767f53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-01-19T11:59:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T08:57:38.000Z", "max_issues_repo_path": "Eg01_UseEigen/main.cpp", "max_issues_repo_name": "chengfzy/SLAM", "max_issues_repo_head_hexsha": "9ea4557d3df6ca9c9552d2b38a3c663241767f53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Eg01_UseEigen/main.cpp", "max_forks_repo_name": "chengfzy/SLAM", "max_forks_repo_head_hexsha": "9ea4557d3df6ca9c9552d2b38a3c663241767f53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-12-07T02:49:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:27:13.000Z", "avg_line_length": 33.5833333333, "max_line_length": 115, "alphanum_fraction": 0.5967741935, "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7897368492901005}} {"text": "// find_scale.cpp\n\n// Copyright Paul A. Bristow 2007, 2010.\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Example of finding scale (standard deviation) for normal (Gaussian).\n\n// Note that this file contains Quickbook mark-up as well as code\n// and comments, don't change any of the special comment mark-ups!\n\n//[find_scale1\n/*`\nFirst we need some includes to access the __normal_distrib,\nthe algorithms to find scale (and some std output of course).\n*/\n\n#include // for normal_distribution\n using boost::math::normal; // typedef provides default type is double.\n#include \n using boost::math::find_scale;\n using boost::math::complement; // Needed if you want to use the complement version.\n using boost::math::policies::policy; // Needed to specify the error handling policy.\n\n#include \n using std::cout; using std::endl;\n#include \n using std::setw; using std::setprecision;\n#include \n using std::numeric_limits;\n//] [/find_scale1]\n\nint main()\n{\n cout << \"Example: Find scale (standard deviation).\" << endl;\n try\n {\n//[find_scale2\n/*`\nFor this example, we will use the standard __normal_distrib,\nwith location (mean) zero and standard deviation (scale) unity.\nConveniently, this is also the default for this implementation's constructor.\n*/\n normal N01; // Default 'standard' normal distribution with zero mean\n double sd = 1.; // and standard deviation is 1.\n/*`Suppose we want to find a different normal distribution with standard deviation\nso that only fraction p (here 0.001 or 0.1%) are below a certain chosen limit\n(here -2. standard deviations).\n*/\n double z = -2.; // z to give prob p\n double p = 0.001; // only 0.1% below z = -2\n\n cout << \"Normal distribution with mean = \" << N01.location() // aka N01.mean()\n << \", standard deviation \" << N01.scale() // aka N01.standard_deviation()\n << \", has \" << \"fraction <= \" << z\n << \", p = \" << cdf(N01, z) << endl;\n cout << \"Normal distribution with mean = \" << N01.location()\n << \", standard deviation \" << N01.scale()\n << \", has \" << \"fraction > \" << z\n << \", p = \" << cdf(complement(N01, z)) << endl; // Note: uses complement.\n/*`\n[pre\nNormal distribution with mean = 0 has fraction <= -2, p = 0.0227501\nNormal distribution with mean = 0 has fraction > -2, p = 0.97725\n]\nNoting that p = 0.02 instead of our target of 0.001,\nwe can now use `find_scale` to give a new standard deviation.\n*/\n double l = N01.location();\n double s = find_scale(z, p, l);\n cout << \"scale (standard deviation) = \" << s << endl;\n/*`\nthat outputs:\n[pre\nscale (standard deviation) = 0.647201\n]\nshowing that we need to reduce the standard deviation from 1. to 0.65.\n\nThen we can check that we have achieved our objective\nby constructing a new distribution\nwith the new standard deviation (but same zero mean):\n*/\n normal np001pc(N01.location(), s);\n/*`\nAnd re-calculating the fraction below (and above) our chosen limit.\n*/\n cout << \"Normal distribution with mean = \" << l\n << \" has \" << \"fraction <= \" << z\n << \", p = \" << cdf(np001pc, z) << endl;\n cout << \"Normal distribution with mean = \" << l\n << \" has \" << \"fraction > \" << z\n << \", p = \" << cdf(complement(np001pc, z)) << endl;\n/*`\n[pre\nNormal distribution with mean = 0 has fraction <= -2, p = 0.001\nNormal distribution with mean = 0 has fraction > -2, p = 0.999\n]\n\n[h4 Controlling how Errors from find_scale are handled]\nWe can also control the policy for handling various errors.\nFor example, we can define a new (possibly unwise)\npolicy to ignore domain errors ('bad' arguments).\n\nUnless we are using the boost::math namespace, we will need:\n*/\n using boost::math::policies::policy;\n using boost::math::policies::domain_error;\n using boost::math::policies::ignore_error;\n\n/*`\nUsing a typedef is convenient, especially if it is re-used,\nalthough it is not required, as the various examples below show.\n*/\n typedef policy > ignore_domain_policy;\n // find_scale with new policy, using typedef.\n l = find_scale(z, p, l, ignore_domain_policy());\n // Default policy policy<>, needs using boost::math::policies::policy;\n\n l = find_scale(z, p, l, policy<>());\n // Default policy, fully specified.\n l = find_scale(z, p, l, boost::math::policies::policy<>());\n // New policy, without typedef.\n l = find_scale(z, p, l, policy >());\n/*`\nIf we want to express a probability, say 0.999, that is a complement, `1 - p`\nwe should not even think of writing `find_scale(z, 1 - p, l)`,\nbut use the __complements version (see __why_complements).\n*/\n z = -2.;\n double q = 0.999; // = 1 - p; // complement of 0.001.\n sd = find_scale(complement(z, q, l));\n\n normal np95pc(l, sd); // Same standard_deviation (scale) but with mean(scale) shifted\n cout << \"Normal distribution with mean = \" << l << \" has \"\n << \"fraction <= \" << z << \" = \" << cdf(np95pc, z) << endl;\n cout << \"Normal distribution with mean = \" << l << \" has \"\n << \"fraction > \" << z << \" = \" << cdf(complement(np95pc, z)) << endl;\n\n/*`\nSadly, it is all too easy to get probabilities the wrong way round,\nwhen you may get a warning like this:\n[pre\nMessage from thrown exception was:\n Error in function boost::math::find_scale(complement(double, double, double, Policy)):\n Computed scale (-0.48043523852179076) is <= 0! Was the complement intended?\n]\nThe default error handling policy is to throw an exception with this message,\nbut if you chose a policy to ignore the error,\nthe (impossible) negative scale is quietly returned.\n*/\n//] [/find_scale2]\n }\n catch(const std::exception& e)\n { // Always useful to include try & catch blocks because default policies\n // are to throw exceptions on arguments that cause errors like underflow, overflow.\n // Lacking try & catch blocks, the program will abort without a message below,\n // which may give some helpful clues as to the cause of the exception.\n std::cout <<\n \"\\n\"\"Message from thrown exception was:\\n \" << e.what() << std::endl;\n }\n return 0;\n} // int main()\n\n//[find_scale_example_output\n/*`\n[pre\nExample: Find scale (standard deviation).\nNormal distribution with mean = 0, standard deviation 1, has fraction <= -2, p = 0.0227501\nNormal distribution with mean = 0, standard deviation 1, has fraction > -2, p = 0.97725\nscale (standard deviation) = 0.647201\nNormal distribution with mean = 0 has fraction <= -2, p = 0.001\nNormal distribution with mean = 0 has fraction > -2, p = 0.999\nNormal distribution with mean = 0.946339 has fraction <= -2 = 0.001\nNormal distribution with mean = 0.946339 has fraction > -2 = 0.999\n]\n*/\n//] [/find_scale_example_output]\n", "meta": {"hexsha": "29e474f0f3a874b62d1d5782eedd4e90f4b0faec", "size": 6934, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/example/find_scale_example.cpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/libs/math/example/find_scale_example.cpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/libs/math/example/find_scale_example.cpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 38.3093922652, "max_line_length": 103, "alphanum_fraction": 0.6835881165, "num_tokens": 1889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.8947894731166139, "lm_q1q2_score": 0.7895871656882318}} {"text": "#include \n#include \n#include \n\nusing namespace std;\nusing namespace Eigen;\n\nint main(void)\n{\n double theta = M_PI/6;\n Matrix2d rot;\n rot <<\n cos(theta), -sin(theta),\n sin(theta), cos(theta);\n auto trans_rot = rot.transpose();\n auto inv_rot = rot.inverse();\n\n cout << \"==================\" << endl;\n cout << rot << endl;\n cout << \"==================\" << endl;\n cout << trans_rot << endl;\n cout << \"==================\" << endl;\n cout << inv_rot << endl;\n cout << \"==================\" << endl;\n cout << rot*trans_rot << endl;\n cout << \"==================\" << endl;\n\n Matrix2d test;\n test <<\n 2,3,\n 6,4;\n cout << \"==================\" << endl;\n cout << test << endl;\n cout << \"==================\" << endl;\n cout << test.inverse() << endl;\n cout << \"==================\" << endl;\n cout << test * test.inverse() << endl;\n cout << \"==================\" << endl;\n\n\n\n\n \n \n return 0;\n}\n", "meta": {"hexsha": "f38df6be088cbbd51a7bc9a8cfccbeb10b43c914", "size": 948, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/orthogonal_matrix.cpp", "max_stars_repo_name": "RyodoTanaka/eigen_example", "max_stars_repo_head_hexsha": "55da46919e02d0eb7cbea9da97ffa0f9067a6d98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/orthogonal_matrix.cpp", "max_issues_repo_name": "RyodoTanaka/eigen_example", "max_issues_repo_head_hexsha": "55da46919e02d0eb7cbea9da97ffa0f9067a6d98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/orthogonal_matrix.cpp", "max_forks_repo_name": "RyodoTanaka/eigen_example", "max_forks_repo_head_hexsha": "55da46919e02d0eb7cbea9da97ffa0f9067a6d98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-30T03:32:04.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-30T03:32:04.000Z", "avg_line_length": 20.170212766, "max_line_length": 40, "alphanum_fraction": 0.4451476793, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538936, "lm_q2_score": 0.8354835289107307, "lm_q1q2_score": 0.7895275204213461}} {"text": "#include \"Util.h\"\n\n#include \n\n#include \n#include \n\nusing namespace std;\n\nfloat Ubpa::MutualCoherence(const Eigen::MatrixXf& A) {\n\tsize_t N = A.cols();\n\n\tvector norms(N);\n\n\tfor (size_t i = 0; i < N; i++)\n\t\tnorms[i] = A.col(i).norm();\n\n\tfloat max = 0.f;\n\n\tfor (size_t i = 0; i < N; i++) {\n\t\tfor (size_t j = i + 1; j < N; j++) {\n\t\t\tfloat ai_dot_aj = A.col(i).dot(A.col(j));\n\t\t\tfloat val = std::abs(ai_dot_aj) / norms[i] / norms[j];\n\t\t\tif (val > max)\n\t\t\t\tmax = val;\n\t\t}\n\t}\n\n\treturn max;\n}\n\nEigen::VectorXf Ubpa::Shrink(const Eigen::VectorXf& z, float tau) {\n\tassert(tau > 0);\n\n\tsize_t N = z.size();\n\n\tEigen::VectorXf x(N);\n\n\tfor (size_t i = 0; i < N; i++) {\n\t\tif (z[i] > tau)\n\t\t\tx[i] = z[i] - tau;\n\t\telse if (z[i] < -tau)\n\t\t\tx[i] = z[i] + tau;\n\t\telse\n\t\t\tx[i] = 0.f;\n\t}\n\n\treturn x;\n}\n\nEigen::VectorXf Ubpa::MoreauYosidaRegularization_Norm1(const Eigen::VectorXf& z, float tau) {\n\treturn Shrink(z, tau);\n}\n\nEigen::VectorXf Ubpa::MoreauYosidaRegularization_Norm2(const Eigen::VectorXf& z, float tau)\n{\n\tassert(tau > 0);\n\n\tfloat normZ = z.norm();\n\tfloat coff = std::max(normZ - tau, 0.f);\n\n\tEigen::VectorXf x = coff / normZ * z;\n\n\treturn x;\n}\n\nEigen::MatrixXf Ubpa::MoreauYosidaRegularization_NormNuclear(const Eigen::MatrixXf& Z, float tau)\n{\n\t// ? : Eigen::ComputeThinU | Eigen::ComputeThinV\n\tEigen::JacobiSVD svd(Z, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\t// Z = U * S * V^T\n\tEigen::MatrixXf U = svd.matrixU();\n\tEigen::MatrixXf V = svd.matrixV();\n\tEigen::MatrixXf S = U.inverse() * Z * V.transpose().inverse();\n\n\tEigen::VectorXf Z_diag = S.diagonal();\n\tEigen::VectorXf X_diag = Shrink(Z_diag, tau);\n\t\n\tEigen::MatrixXf X_S = Eigen::MatrixXf::Zero(Z_diag.size(), Z_diag.size());\n\tfor (size_t i = 0; i < Z_diag.size(); i++)\n\t\tX_S(i, i) = X_diag(i);\n\n\tEigen::MatrixXf X = U * X_S * V.transpose();\n\n\treturn X;\n}\n\nbool Ubpa::ADMM::CheckSettingValid() const {\n\tif (mu <= 0.f)\n\t\treturn false;\n\n\tif (rho <= 0.f)\n\t\treturn false;\n\n\tif (alpha < 1.f)\n\t\treturn false;\n\n\tif (beta >= 1.f || beta <= 0.f)\n\t\treturn false;\n\n\tif (epsilon <= 0.f)\n\t\treturn false;\n\n\tif (epsilon <= 0.f)\n\t\treturn false;\n\n\treturn true;\n}\n\nbool Ubpa::ADMM::SetProblem(Eigen::MatrixXf A, Eigen::VectorXf b) {\n\tif (A.rows() != b.size())\n\t\treturn false;\n\n\tthis->A = std::move(A);\n\tthis->b = std::move(b);\n\tm = this->A.rows();\n\tn = this->A.cols();\n\n\treturn true;\n}\n\n// set\n// - x, y, z, u_y, u_z\n// - cur_rho, last_residule\nvoid Ubpa::ADMM::Init() {\n\tx.setZero(n);\n\ty.setZero(m);\n\tz.setZero(n);\n\n\tu_y.setZero(m);\n\tu_z.setZero(n);\n\n\tcur_rho = rho;\n\tlast_residule = b.norm();\n}\n\nvoid Ubpa::ADMM::Iterate() {\n\t// common\n\tEigen::MatrixXf AT = A.transpose();\n\tEigen::VectorXf Ax = A * x;\n\n\t// [[ phase 1 ]]\n\t// update x, y, z\n\t// [formula]\n\t// x := argmin_x (x-z+u_z)^2 + (Ax-y-b+u_y)^2\n\t// y := argmin_y ||y||_q + rho/2 * (y-Ax+b-u_y)^2\n\t// z := argmin_z mu * ||z||_p + rho/2 * (z-x-u_z)^2\n\t// [result]\n\t// - x\n\t// (x-z+u_z) + A^T(Ax-y-b+u_y) = 0\n\t// => x = (I + A^T A)^-1 (z - u_z + A^T(y + b - u_y))\n\t// - y\n\t// y = MoreauYosidaRegularization_Norm*(Ax-b+u_y, 1/rho)\n\t// - z\n\t// z = MoreauYosidaRegularization_Norm*(x+u_z, mu/rho)\n\n\tx = (Eigen::MatrixXf::Identity(n, n) + AT * A).inverse() * (z - u_z + AT * (y + b - u_y));\n\tswitch (q)\n\t{\n\tcase Ubpa::ADMM::Norm::One:\n\t\ty = MoreauYosidaRegularization_Norm1(Ax - b + u_y, 1 / cur_rho);\n\t\tbreak;\n\tcase Ubpa::ADMM::Norm::Two:\n\t\ty = MoreauYosidaRegularization_Norm2(Ax - b + u_y, 1 / cur_rho);\n\t\tbreak;\n\tdefault:\n\t\tassert(true && \"not support\");\n\t\tbreak;\n\t}\n\tswitch (p)\n\t{\n\tcase Ubpa::ADMM::Norm::One:\n\t\tz = MoreauYosidaRegularization_Norm1(x + u_z, mu / cur_rho);\n\t\tbreak;\n\tcase Ubpa::ADMM::Norm::Two:\n\t\tz = MoreauYosidaRegularization_Norm2(x + u_z, mu / cur_rho);\n\t\tbreak;\n\tdefault:\n\t\tassert(true && \"not support\");\n\t\tbreak;\n\t}\n\n\t// [[ phase 2 ]]\n\t// update u_y, u_z\n\t// [formula]\n\t// u_y := u_y + gamma * (Ax - y - b)\n\t// u_z := u_z + gamma * (x - z)\n\n\tu_y += gamma * (Ax - y - b);\n\tu_z += gamma * (x - z);\n\n\t// [[ phase 3 ]]\n\t// update current settings: last_residule, cur_rho\n\n\tfloat cur_residule = std::sqrt((x - z).squaredNorm() + (Ax - y - b).squaredNorm());\n\tif (cur_residule / last_residule >= beta)\n\t\tcur_rho *= alpha;\n\n\tlast_residule = cur_residule;\n}\n\nbool Ubpa::ADMM::IsStoppable() {\n\treturn last_residule < epsilon;\n}\n", "meta": {"hexsha": "ff47af58d40357bd368d74f77ece5309288598bd", "size": 4293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2020Spring/Optimization/homeworks/final/sparse/src/core/Util.cpp", "max_stars_repo_name": "Ubpa/MasterCourses", "max_stars_repo_head_hexsha": "46ea8ae8088d5787af277d33beabd02a2766fcc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-09-10T13:25:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T16:01:03.000Z", "max_issues_repo_path": "2020Spring/Optimization/homeworks/final/sparse/src/core/Util.cpp", "max_issues_repo_name": "Ubpa/MasterCourses", "max_issues_repo_head_hexsha": "46ea8ae8088d5787af277d33beabd02a2766fcc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020Spring/Optimization/homeworks/final/sparse/src/core/Util.cpp", "max_forks_repo_name": "Ubpa/MasterCourses", "max_forks_repo_head_hexsha": "46ea8ae8088d5787af277d33beabd02a2766fcc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-04T09:30:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-04T09:30:48.000Z", "avg_line_length": 20.9414634146, "max_line_length": 97, "alphanum_fraction": 0.594921966, "num_tokens": 1587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7895275197565897}} {"text": "#include \n#include \n\nusing namespace std;\n\n#include \n#include \n\nint main()\n{\n // Eigen/Geometry provides various representation for rotation and translation\n Eigen::Matrix3d rotation_matrix = Eigen::Matrix3d::Identity();\n // rotation vector with AngleAxis, it's not matrix in bottom, but could be calculated as matrix due to overloading\n // rotate 45 deg about z\n Eigen::AngleAxisd rotation_vector(M_PI/4, Eigen::Vector3d(0, 0, 1));\n cout.precision(3);\n cout << \"rotation matrix = \\n\" << rotation_vector.matrix() << endl;\n rotation_matrix = rotation_vector.toRotationMatrix();\n // coordinate transformation with AngleAxis\n Eigen::Vector3d v(1, 0, 0);\n Eigen::Vector3d v_rotated = rotation_vector * v; // can do this directly?\n cout << \"(1, 0, 0) after rotation: \" << v_rotated.transpose() << endl;\n // or use rotation matrix\n v_rotated = rotation_matrix * v;\n cout << \"(1, 0, 0) after rotation: \" << v_rotated.transpose() << endl;\n\n // Euler angles\n // ZYX order, i.e. yaw pitch roll\n // R = Rz*Ry*Rx from body to fixed frame\n Eigen::Vector3d euler_angles = rotation_matrix.eulerAngles(2, 1, 0);\n cout << \"yaw pitch roll: \" << euler_angles.transpose() << endl;\n // Euler transformation with Isometry\n Eigen::Isometry3d T = Eigen::Isometry3d::Identity(); // called 3d, actually 4x4\n T.rotate(rotation_vector); // rotate about rotation_vector\n cout << \"Transformation matrix: \\n\" << T.matrix() << endl;\n T.pretranslate(Eigen::Vector3d(1, 3, 4)); // translate by (1, 3, 4);\n cout << \"Transformation matrix: \\n\" << T.matrix() << endl;\n\n // coordinate transformation with Transformation matrix\n Eigen::Vector3d v_transformed = T*v; // Notice we don't need T.matrix()*v; nor need extend v to be 4x1\n cout << \"v transformed: \" << v_transformed.transpose() << endl;\n\n // Eigen::Affine3d and Eigen::Projective3d\n // TODO\n\n // Quaternion\n // from AngleAxis\n Eigen::Quaterniond q = Eigen::Quaterniond(rotation_vector);\n cout << \"quaternions: \\n\" << q.coeffs().transpose() << endl;\n // notice, this order is (x, y, z, w) with imaginary coefficients first\n // while in constructing Quaternion from coefficients the required order is (w, x, y, z)\n // based on Eigen doc; but internally the stored coefficients are in oder of (x, y, z, w) - annoying\n // from rotation matrix\n q = Eigen::Quaterniond(rotation_matrix);\n cout << \"quaternions: \\n\" << q.coeffs().transpose() << endl;\n // use quaternion to rotate one vector\n v_rotated = q*v; // mathematically, qvq^{-1}\n cout << \"(1, 0, 0) after rotation: \" << v_rotated.transpose() << endl;\n\n return 0;\n\n /* Summary of various transformation expression in Eigen\n * rotation matrix (3x3): Eigen::Matrix3d\n * angle-axis (3x1): Eigen::AngleAxisd - interesting one\n * euler angles (3x1): Eigen::Vector3d\n * quaternion (3x1): Eigen::Quaterniond\n * homogeneous transformation (4x4): Eigen::Isometry3d\n * affine (4x4): Eigen::Affine3d\n * projection (4x4): Eigen::Projective3d\n */\n}\n", "meta": {"hexsha": "acaaed49bce551845fc4fe1c0013def00a971880", "size": 3219, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch03/useGeometry/eigenGeometry.cpp", "max_stars_repo_name": "sunoval2016/SLAM-14", "max_stars_repo_head_hexsha": "72d848c159ff766d87c9bc3c0a170f84745a3785", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch03/useGeometry/eigenGeometry.cpp", "max_issues_repo_name": "sunoval2016/SLAM-14", "max_issues_repo_head_hexsha": "72d848c159ff766d87c9bc3c0a170f84745a3785", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch03/useGeometry/eigenGeometry.cpp", "max_forks_repo_name": "sunoval2016/SLAM-14", "max_forks_repo_head_hexsha": "72d848c159ff766d87c9bc3c0a170f84745a3785", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.7083333333, "max_line_length": 118, "alphanum_fraction": 0.64305685, "num_tokens": 874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7893343418885664}} {"text": "/**\n * KalmanFilter.hpp\n * @author : koide\n * 13/08/04\n **/\n#ifndef KKL_KALMAN_FILTER_HPP\n#define KKL_KALMAN_FILTER_HPP\n\n#include \n\nnamespace kkl{\n namespace alg{\n\n/*****************************************************\n * Kalman filter\n * T : type of scalar\n * stateDim : dimension of the state\n * inputDim : dimension of the input\n * measurementDim : dimension of the observation\n*****************************************************/\ntemplate\nclass KalmanFilter{\n const static int N = stateDim;\n const static int M = inputDim;\n const static int K = measurementDim;\n\n typedef Eigen::Matrix VectorN;\n typedef Eigen::Matrix VectorM;\n typedef Eigen::Matrix VectorK;\n typedef Eigen::Matrix MatrixNN;\n typedef Eigen::Matrix MatrixNM;\n typedef Eigen::Matrix MatrixKK;\n typedef Eigen::Matrix MatrixKN;\n typedef Eigen::Matrix MatrixNK;\npublic:\n\n /*****************************************************************\n * constructor\n * transition\t\t : state transition matrix\n * control\t\t\t : input response matrix\n * measurement\t\t : observation matrix\n * processNoise\t\t : process noise covariance matrix\n * measurementNoise : measurement noise covariance matrix\n * mean\t\t\t\t : initial mean\n * cov\t\t\t\t : initial covariance matrix\n *****************************************************************/\n KalmanFilter( const MatrixNN& transition, const MatrixNM& control, const MatrixKN& measurement, const MatrixNN& processNoise, const MatrixKK& measurementNoise, const VectorN& mean, const MatrixNN& cov )\n : mean( mean ),\n cov( cov ),\n transitionMatrix( transition ),\n controlMatrix( control ),\n measurementMatrix( measurement ),\n processNoiseCov( processNoise ),\n measurementNoiseCov( measurementNoise ){}\n\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n /*****************************************************************\n * predict\n * control : input\n *****************************************************************/\n void predict( const VectorM& control ){\n const auto& A = transitionMatrix;\n const auto& B = controlMatrix;\n const auto& R = processNoiseCov;\n\n const auto& u = control;\n\n mean = A * mean + B * u;\n cov = A * cov * A.transpose() + R;\n }\n\n /*****************************************************************\n * correct\n * measurement : measurement vector\n *****************************************************************/\n void correct( const VectorK& measurement ){\n const auto& C = measurementMatrix;\n const auto& Q = measurementNoiseCov;\n\n kalmanGain = cov * C.transpose() * ( C * cov * C.transpose() + Q ).inverse();\n const auto& K = kalmanGain;\n\n mean = mean + K * ( measurement - C * mean );\n cov = ( MatrixNN::Identity() - K * C ) * cov;\n }\n\n /*\t\t\tgetter\t\t\t*/\n const VectorN& getMean() const { return mean; }\n const MatrixNN& getCov() const { return cov; }\n\n const MatrixNN& getTransitionMatrix() const { return transitionMatrix; }\n const MatrixNM& getControlMatrix() const { return controlMatrix; }\n const MatrixKN& getMeasurementMatrix() const { return measurementMatrix; }\n\n const MatrixNN& getProcessNoiseCov() const { return processNoiseCov; }\n const MatrixKK& getMeasurementNoiseCov() const { return measurementNoiseCov; }\n\n const MatrixNK& getKalmanGain() const { return kalmanGain; }\n\n /*\t\t\tsetter\t\t\t*/\n KalmanFilter& setMean( const VectorN& m ){ mean = m;\t\t\treturn *this; }\n KalmanFilter& setCov( const MatrixNN& s ){ cov = s;\t\t\treturn *this; }\n\n KalmanFilter& setTransitionMatrix( const MatrixNN& t ){ transitionMatrix = t;\treturn *this; }\n KalmanFilter& setControlMatrix( const MatrixNM& c ){ controlMatrix = c;\t\t\treturn *this; }\n KalmanFilter& setMeasurementMatrix( const MatrixKN& m ){ measurementMatrix = m;\treturn *this; }\n\n KalmanFilter& setProcessNoiseCov( const MatrixNN& p ){ processNoiseCov = p;\t\t\treturn *this; }\n KalmanFilter& setMeasurementNoiseCov( const MatrixKK& m ){ measurementNoiseCov = m;\treturn *this; }\npublic:\n VectorN mean;\t\t\t// mean of the state\n MatrixNN cov;\t\t\t// covariance of the state\n\n MatrixNN transitionMatrix;\t\t//\n MatrixNM controlMatrix;\t\t\t//\n MatrixKN measurementMatrix;\t\t//\n MatrixNN processNoiseCov;\t\t//\n MatrixKK measurementNoiseCov;\t//\n\nprivate:\n MatrixNK kalmanGain;\n};\n }\n}\n\n#endif\n", "meta": {"hexsha": "38c7e69a706532f9d713851614d0b8ee34b4b92a", "size": 4405, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kkl/alg/kalman_filter.hpp", "max_stars_repo_name": "y-lai/hdl_people_tracking", "max_stars_repo_head_hexsha": "fb7ec799047b8ea833a175abd2599793b8966c24", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 207.0, "max_stars_repo_stars_event_min_datetime": "2018-03-10T14:56:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T07:32:53.000Z", "max_issues_repo_path": "include/kkl/alg/kalman_filter.hpp", "max_issues_repo_name": "y-lai/hdl_people_tracking", "max_issues_repo_head_hexsha": "fb7ec799047b8ea833a175abd2599793b8966c24", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2018-02-19T10:50:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T19:44:55.000Z", "max_forks_repo_path": "include/kkl/alg/kalman_filter.hpp", "max_forks_repo_name": "y-lai/hdl_people_tracking", "max_forks_repo_head_hexsha": "fb7ec799047b8ea833a175abd2599793b8966c24", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 91.0, "max_forks_repo_forks_event_min_datetime": "2018-02-23T09:44:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T01:38:14.000Z", "avg_line_length": 34.4140625, "max_line_length": 204, "alphanum_fraction": 0.6113507378, "num_tokens": 1074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474155747541, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.789218269483073}} {"text": "#include \"Triangle.h\"\n#include \"Ray.h\"\n#include \n#include \n\nbool Triangle::intersect(\n const Ray & ray, const double min_t, double & t, Eigen::Vector3d & n) const\n{\n ////////////////////////////////////////////////////////////////////////////\n /**\n * NOTE: The following solution is found on page 79 in the textbook.\n */\n bool hit = false;\n\n // Set up some variables\n Eigen::Vector3d P = std::get<0>(Triangle::corners); // Point P\n Eigen::Vector3d Q = std::get<1>(Triangle::corners); // Point Q\n Eigen::Vector3d R = std::get<2>(Triangle::corners); // Point R\n Eigen::Vector3d PQ = Q - P; // direction vector\n Eigen::Vector3d PR = R - P; // direction vector\n Eigen::Vector3d v = ray.direction;\n Eigen::Vector3d O = ray.origin;\n\n // Get the normal of the two vectors in the plane of the triangle\n Eigen::Vector3d normal = PQ.cross(PR);\n\n // Check if the ray intersects with the plane made by the triangle\n if (v.dot(normal) == 0) {\n return false;\n }\n\n // If we make it here, then we know that the ray intersects the plane at some\n // point t\n t = (normal.dot(P - O)) / (normal.dot(v));\n if (t < min_t) {\n return false;\n }\n\n /**\n * Now we need to check if the intersection point is in the triangle\n */\n // Eigen::Matrix3d A;\n // A << -PQ, -PR, v;\n // Eigen::Vector3d y = P - O; // Ax = y, where x = \n\n // Set up the columns of matrix A\n // Column vector (P - Q)\n double a = -PQ[0];\n double b = -PQ[1];\n double c = -PQ[2];\n // Column vector (P - R)\n double d = -PR[0];\n double e = -PR[1];\n double f = -PR[2];\n // Column vector d (direction vector of ray)\n double g = v[0];\n double h = v[1];\n double i = v[2];\n\n // Column vector y Ax = y\n double j = P[0] - O[0];\n double k = P[1] - O[1];\n double l = P[2] - O[2];\n\n /**\n * Rather than use A.determinant(), we can reduce the number of operations\n * by reusing numbers.\n * double M = A.determinant();\n */\n double ei_minus_hf = e * i - h * f;\n double gf_minus_di = g * f - d * i;\n double dh_minus_eg = d * h - e * g;\n\n double ak_minus_jb = a * k - j * b;\n double jc_minus_al = j * c - a * l;\n double bl_minus_kc = b * l - k * c;\n\n // Get the determinant of A\n double M = a * ei_minus_hf + b * gf_minus_di + c * dh_minus_eg;\n\n // Solve for the values of x = in the system Ax = y\n double beta = (j * ei_minus_hf + k * gf_minus_di + l * dh_minus_eg) / M;\n double gamma = (i * ak_minus_jb + h * jc_minus_al + g * bl_minus_kc) / M;\n // double t_prime = -((f * ak_minus_jb + e * jc_minus_al + d * bl_minus_kc) / M);\n // assert(t == t_prime); // works properly\n\n if (beta >= 0 && gamma >= 0 && (beta + gamma) <= 1) {\n n = normal.normalized();\n hit = true;\n }\n\n return hit;\n ////////////////////////////////////////////////////////////////////////////\n}\n", "meta": {"hexsha": "9fd13e3c12e40880d448ff183ce76eae24b6ab36", "size": 2961, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Triangle.cpp", "max_stars_repo_name": "ericpko/computer-graphics-ray-tracing", "max_stars_repo_head_hexsha": "033293a94a5076c79c1fc7d3dac8931fdab6a44c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Triangle.cpp", "max_issues_repo_name": "ericpko/computer-graphics-ray-tracing", "max_issues_repo_head_hexsha": "033293a94a5076c79c1fc7d3dac8931fdab6a44c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Triangle.cpp", "max_forks_repo_name": "ericpko/computer-graphics-ray-tracing", "max_forks_repo_head_hexsha": "033293a94a5076c79c1fc7d3dac8931fdab6a44c", "max_forks_repo_licenses": ["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.1684210526, "max_line_length": 83, "alphanum_fraction": 0.5396825397, "num_tokens": 896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7889680784579275}} {"text": "// students_t_example2.cpp\n\n// Copyright Paul A. Bristow 2006.\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Example 2 of using Student's t\n\n// A general guide to Student's t is at\n// http://en.wikipedia.org/wiki/Student's_t-test\n// (and many other elementary and advanced statistics texts).\n// It says:\n// The t statistic was invented by William Sealy Gosset\n// for cheaply monitoring the quality of beer brews.\n// \"Student\" was his pen name.\n// Gosset was statistician for Guinness brewery in Dublin, Ireland,\n// hired due to Claude Guinness's innovative policy of recruiting the\n// best graduates from Oxford and Cambridge for applying biochemistry\n// and statistics to Guinness's industrial processes.\n// Gosset published the t test in Biometrika in 1908,\n// but was forced to use a pen name by his employer who regarded the fact\n// that they were using statistics as a trade secret.\n// In fact, Gosset's identity was unknown not only to fellow statisticians\n// but to his employer - the company insisted on the pseudonym\n// so that it could turn a blind eye to the breach of its rules.\n\n// The Students't distribution function is described at\n// http://en.wikipedia.org/wiki/Student%27s_t_distribution\n\n#include \n using boost::math::students_t; // Probability of students_t(df, t).\n\n#include \n using std::cout;\n using std::endl;\n#include \n using std::setprecision;\n using std::setw;\n#include \n using std::sqrt;\n\n// This example of a one-sided test is from:\n//\n// from Statistics for Analytical Chemistry, 3rd ed. (1994), pp 59-60\n// J. C. Miller and J. N. Miller, Ellis Horwood ISBN 0 13 0309907.\n\n// An acid-base titrimetric method has a significant indicator error and\n// thus tends to give results with a positive systematic error (+bias).\n// To test this an exactly 0.1 M solution of acid is used to titrate\n// 25.00 ml of exactly 0.1 M solution of alkali,\n// with the following results (ml):\n\ndouble reference = 25.00; // 'True' result.\nconst int values = 6; // titrations.\ndouble data [values] = {25.06, 25.18, 24.87, 25.51, 25.34, 25.41};\n\nint main()\n{\n cout << \"Example2 using Student's t function. \";\n#if defined(__FILE__) && defined(__TIMESTAMP__) && defined(_MSC_FULL_VER)\n cout << \" \" << __FILE__ << ' ' << __TIMESTAMP__ << ' '<< _MSC_FULL_VER;\n#endif\n cout << endl;\n\n double sum = 0.;\n for (int value = 0; value < values; value++)\n { // Echo data and calculate mean.\n sum += data[value];\n cout << setw(4) << value << ' ' << setw(14) << data[value] << endl;\n }\n double mean = sum /static_cast(values);\n cout << \"Mean = \" << mean << endl; // 25.2283\n\n double sd = 0.;\n for (int value = 0; value < values; value++)\n { // Calculate standard deviation.\n sd +=(data[value] - mean) * (data[value] - mean);\n }\n int degrees_of_freedom = values - 1; // Use the n-1 formula.\n sd /= degrees_of_freedom; // == variance.\n sd= sqrt(sd);\n cout << \"Standard deviation = \" << sd<< endl; // = 0.238279\n\n double t = (mean - reference) * sqrt(static_cast(values))/ sd; //\n cout << \"Student's t = \" << t << \", with \" << degrees_of_freedom << \" degrees of freedom.\" << endl; // = 2.34725\n\n cout << \"Probability of positive bias is \" << cdf(students_t(degrees_of_freedom), t) << \".\"<< endl; // = 0.967108.\n // A 1-sided test because only testing for a positive bias.\n // If > 0.95 then greater than 1 in 20 conventional (arbitrary) requirement.\n\n return 0;\n} // int main()\n\n/*\n\nOutput is:\n\n------ Build started: Project: students_t_example2, Configuration: Debug Win32 ------\nCompiling...\nstudents_t_example2.cpp\nLinking...\nAutorun \"i:\\boost-06-05-03-1300\\libs\\math\\test\\Math_test\\debug\\students_t_example2.exe\"\nExample2 using Student's t function. ..\\..\\..\\..\\..\\..\\boost-sandbox\\libs\\math_functions\\example\\students_t_example2.cpp Sat Aug 12 16:55:59 2006 140050727\n 0 25.06\n 1 25.18\n 2 24.87\n 3 25.51\n 4 25.34\n 5 25.41\nMean = 25.2283\nStandard deviation = 0.238279\nStudent's t = 2.34725, with 5 degrees of freedom.\nProbability of positive bias is 0.967108.\nBuild Time 0:03\nBuild log was saved at \"file://i:\\boost-06-05-03-1300\\libs\\math\\test\\Math_test\\students_t_example2\\Debug\\BuildLog.htm\"\nstudents_t_example2 - 0 error(s), 0 warning(s)\n========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========\n\n*/\n", "meta": {"hexsha": "29619e86288993ea8a3af874726b4d1fdb232c1c", "size": 4592, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/students_t_example2.cpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/students_t_example2.cpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/students_t_example2.cpp", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 37.6393442623, "max_line_length": 157, "alphanum_fraction": 0.6763937282, "num_tokens": 1304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765140114859, "lm_q2_score": 0.8633916117313211, "lm_q1q2_score": 0.7888606380334318}} {"text": "/**\n * @file symplectictimestepping.cc\n * @brief NPDE homework SymplecticTimestepping\n * @copyright Developed at ETH Zurich\n */\n\n#include \n#include \n#include \n\nconstexpr double PI = 3.14159265358979323846;\n\nnamespace SymplecticTimestepping {\n\n/* SAM_LISTING_BEGIN_0 */\nvoid sympTimestep(double tau, Eigen::Vector2d &pq_j) {\n // Coefficients of the method\n const Eigen::Vector3d a{2. / 3., -2. / 3., 1.};\n const Eigen::Vector3d b{7. / 24., 3. / 4., -1. / 24.};\n // Single step\n //====================\n // Your code goes here\n //====================\n}\n/* SAM_LISTING_END_0 */\n\n/* SAM_LISTING_BEGIN_1 */\nvoid sympTimesteppingODETest() {\n int nIter = 7; // total number of iterations\n unsigned int m; // number of equidistant steps\n Eigen::Vector2d approx_sol;\n\n // Initial conditions\n Eigen::Vector2d init_cond;\n init_cond << 0.0, 1.0; // initial conditions\n\n // Evaluating the error at the final step between the approx solutions as\n // given by the symplectic method and the exact solution computed from\n // the anlytic formula.\n double errors[nIter]; // errors vector for all approx. sols\n double tau;\n for (int k = 0; k < nIter; k++) {\n m = 10 * std::pow(2, k);\n //====================\n // Your code goes here\n //====================\n }\n // Printing results\n std::cout << \"Convergence of Symplectic Time Stepping Method:\\n\";\n std::cout << \"\\tM\\t\\terr(M)\\n\";\n for (int k = 0; k < nIter; k++) {\n std::cout << \"\\t\" << 10 * std::pow(2, k) << \"\\t\\t\" << errors[k]\n << std::endl;\n }\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_3 */\nEigen::MatrixXd simulateHamiltonianDynamics(const Eigen::VectorXd &p0,\n const Eigen::VectorXd &q0, double T,\n unsigned int M) {\n int n = p0.size();\n Eigen::MatrixXd PQ(2 * n, M + 1);\n\n // Coefficients of the method\n Eigen::VectorXd a(3);\n a << 2. / 3., -2. / 3., 1.;\n Eigen::VectorXd b(3);\n b << 7. / 24., 3. / 4., -1. / 24.;\n\n double tau = T / M;\n Eigen::VectorXd pj(p0), qj(q0);\n PQ.col(0) << pj, qj;\n //====================\n // Your code goes here\n //====================\n return PQ;\n}\n/* SAM_LISTING_END_3 */\n\n} // namespace SymplecticTimestepping\n", "meta": {"hexsha": "8c0fb097680484e55831930f66f985a48a7d92da", "size": 2271, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/SymplecticTimestepping/templates/symplectictimestepping.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/SymplecticTimestepping/templates/symplectictimestepping.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/SymplecticTimestepping/templates/symplectictimestepping.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 27.6951219512, "max_line_length": 80, "alphanum_fraction": 0.5711140467, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.9136765269395709, "lm_q1q2_score": 0.7888606379546679}} {"text": "/*\n Math.hpp\n ========\n Math functions implementation.\n*/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace PDBTools\n{\n\n////////////////////////////////////////////////////////////////////////////////\n// Using\n////////////////////////////////////////////////////////////////////////////////\n\nusing std::vector;\nusing std::min;\nusing std::max;\nusing std::tuple;\nusing Eigen::RowVector3d;\nusing Eigen::Matrix3d;\nusing Eigen::Dynamic;\nusing Eigen::Matrix;\nusing Eigen::JacobiSVD;\nusing Eigen::ComputeFullU;\nusing Eigen::ComputeFullV;\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Convert Radians To Degrees\n////////////////////////////////////////////////////////////////////////////////\n\ndouble degrees(double radiansAngle)\n{\n return radiansAngle * 180. / M_PI;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Convert Degrees To Radians\n////////////////////////////////////////////////////////////////////////////////\n\ndouble radians(double degreesAngle)\n{\n return degreesAngle * M_PI / 180.;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Calc Vector Angle\n////////////////////////////////////////////////////////////////////////////////\n\ndouble calcVectorAngle(const RowVector3d &coordA, const RowVector3d &coordB)\n{\n return acos(min(max(coordA.dot(coordB) / (coordA.norm() * coordB.norm()), -1.), 1.));\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Calc Rotation Matrix (Right Multiply Matrix)\n////////////////////////////////////////////////////////////////////////////////\n\nMatrix3d calcRotationMatrix(const RowVector3d &rotationAxis, double rotationAngle)\n{\n auto normRotationAxis = rotationAxis.normalized();\n\n double x = normRotationAxis[0], y = normRotationAxis[1], z = normRotationAxis[2],\n s = sin(rotationAngle), c = cos(rotationAngle), _1c = 1. - c;\n\n return (Matrix3d() <<\n c + x * x * _1c, x * y * _1c + z * s, x * z * _1c - y * s,\n x * y * _1c - z * s, c + y * y * _1c, y * z * _1c + x * s,\n x * z * _1c + y * s, y * z * _1c - x * s, c + z * z * _1c).finished();\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Calc Rotation Matrix By Two Vector (Right Multiply Matrix)\n////////////////////////////////////////////////////////////////////////////////\n\nMatrix3d calcRotationMatrixByTwoVector(const RowVector3d &refCoord,\n const RowVector3d &tarCoord)\n{\n return calcRotationMatrix(tarCoord.cross(refCoord),\n calcVectorAngle(tarCoord, refCoord));\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Calc Dihedral Angle\n////////////////////////////////////////////////////////////////////////////////\n\ndouble calcDihedralAngle(const RowVector3d &coordA, const RowVector3d &coordB,\n const RowVector3d &coordC, const RowVector3d &coordD)\n{\n RowVector3d AB = coordB - coordA;\n RowVector3d AC = coordC - coordA;\n RowVector3d DB = coordB - coordD;\n RowVector3d DC = coordC - coordD;\n\n RowVector3d ABAC = AB.cross(AC);\n RowVector3d DBDC = DB.cross(DC);\n\n double dihedralAngle = calcVectorAngle(ABAC, DBDC);\n\n // Calc Sign\n RowVector3d OA = coordA - coordB;\n RowVector3d OC = coordC - coordB;\n RowVector3d OD = coordD - coordB;\n\n double rotationAngle = calcVectorAngle(OC, RowVector3d(1., 0., 0.));\n\n Matrix3d rotationMatrix = calcRotationMatrix(OC.cross(RowVector3d(1., 0., 0.)),\n rotationAngle);\n\n OA *= rotationMatrix;\n OD *= rotationMatrix;\n\n OA[0] = 0.;\n OD[0] = 0.;\n\n rotationAngle = calcVectorAngle(OA, RowVector3d(0., 0., 1.));\n rotationMatrix = calcRotationMatrix(OA.cross(RowVector3d(0., 0., 1.)), rotationAngle);\n\n OD *= rotationMatrix;\n\n if (OD[1] > 0.)\n {\n dihedralAngle = -dihedralAngle;\n }\n\n return dihedralAngle;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Calc RMSD (Root-Mean-Square Deviation)\n////////////////////////////////////////////////////////////////////////////////\n\ndouble calcRMSD(const Matrix &coordMatrixA,\n const Matrix &coordMatrixB)\n{\n return sqrt((coordMatrixA - coordMatrixB).array().square().sum() / coordMatrixA.rows());\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Calc Superimpose Rotation Matrix (Kabsch Algorithm)\n////////////////////////////////////////////////////////////////////////////////\n\ntuple calcSuperimposeRotationMatrix(\n const Matrix &tarCoordMatrix,\n const Matrix &srcCoordMatrix)\n{\n RowVector3d srcCenterCoord = srcCoordMatrix.colwise().mean();\n RowVector3d tarCenterCoord = tarCoordMatrix.colwise().mean();\n\n JacobiSVD svd(\n (srcCoordMatrix.rowwise() - srcCenterCoord).transpose() *\n (tarCoordMatrix.rowwise() - tarCenterCoord),\n ComputeFullU | ComputeFullV);\n\n Matrix3d U = svd.matrixU(), V = svd.matrixV().transpose();\n\n if (U.determinant() * V.determinant() < 0.)\n {\n U.col(2) = -U.col(2);\n }\n\n auto rotationMatrix = U * V;\n\n return {srcCenterCoord, rotationMatrix, tarCenterCoord};\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Calc RMSD After Superimpose A <= B\n////////////////////////////////////////////////////////////////////////////////\n\ndouble calcRMSDAfterSuperimpose(\n const Matrix &tarCoordMatrix,\n const Matrix &srcCoordMatrix)\n{\n auto [srcCenterCoord, rotationMatrix, tarCenterCoord] =\n calcSuperimposeRotationMatrix(tarCoordMatrix, srcCoordMatrix);\n\n return calcRMSD(tarCoordMatrix, (((srcCoordMatrix.rowwise() - srcCenterCoord) *\n rotationMatrix).rowwise() + tarCenterCoord).eval());\n}\n\n\n} // End namespace PDBTools\n", "meta": {"hexsha": "064ba9083292b6b75ebad3339f5fb5d746ed024d", "size": 6058, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Math.hpp", "max_stars_repo_name": "yingyulou/PDBToolsCpp", "max_stars_repo_head_hexsha": "61d0f72851d42b4f3b06931be4f47d393d82dd2b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-04-16T17:29:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-03T05:19:41.000Z", "max_issues_repo_path": "src/Math.hpp", "max_issues_repo_name": "yingyulou/PDBToolsCpp", "max_issues_repo_head_hexsha": "61d0f72851d42b4f3b06931be4f47d393d82dd2b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math.hpp", "max_forks_repo_name": "yingyulou/PDBToolsCpp", "max_forks_repo_head_hexsha": "61d0f72851d42b4f3b06931be4f47d393d82dd2b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-07-03T05:19:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T08:16:55.000Z", "avg_line_length": 30.4422110553, "max_line_length": 92, "alphanum_fraction": 0.4935622318, "num_tokens": 1323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768572945969, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7888442165160151}} {"text": "//functions to convert from ECEF to ENU and vice-versa\n#include \n\nusing namespace arma;\n\nmat R_ecef_enu(double lat,double lgt,bool give_enu_ecef=false,bool isRadians=false)\n{\n//in the direct version, we are working with the matrix that\n//rotates from ECEF to ENU. If you want from ENU to ECEF, use the third parameter.\n//font: https://en.m.wikipedia.org/wiki/Geographic_coordinate_conversion#Molodensky_transformation\n\n mat res = eye(3,3);\n\n double c = datum::pi/180;\n\n if(isRadians)\n {\n c= 1.0f;\n }\n\n double sLat = sin(lat*c),cLat = cos(lat*c);\n double sLgt = sin(lgt*c),cLgt = cos(lgt*c);\n\n res(0,0)=-sLgt; res(0,1)= cLgt; res(0,2)=0;\n res(1,0)=-sLat*cLgt; res(1,1)=-sLat*sLgt; res(1,2)= cLat;\n res(2,0)= cLat*cLgt; res(2,1)= cLat*sLgt; res(2,2)= sLat;\n\n if(give_enu_ecef)\n {\n res = res.t();\n }\n\n return res;\n}\n\nvec3 ECEF_to_ENU(vec3 vECEF,vec3 v0ECEF,double lat0,double lgt0,bool givenRadians = false)\n{\n //as output an ENU vector\n mat R = R_ecef_enu(lat0,lgt0,false,givenRadians);\n //cout<<\"ECEFtoENU\"<\n#include \n#include \n\n#include \"timer.h\"\n\n//! \\brief Compute the Kronecker product $C = A \\otimes B$.\n//! \\param[in] A Matrix $n \\times n$\n//! \\param[in] B Matrix $n \\times n$\n//! \\param[out] C Kronecker product of A and B of dim $n^2 \\times n^2$\ntemplate \nvoid kron(const Matrix & A, const Matrix & B, Matrix & C)\n{\n // TODO\n}\n\n//! \\brief Compute the Kronecker product C = $A \\otimes B$. Exploit matrix-vector product.\n//! A,B and x must have dimension n \\times n resp. n\n//! \\param[in] A Matrix $n \\times n$\n//! \\param[in] B Matrix $n \\times n$\n//! \\param[in] x Vector of dim $n$\n//! \\param[out] y Vector y = kron(A,B)*x\ntemplate \nvoid kron_fast(const Matrix & A, const Matrix & B, const Vector & x, Vector & y)\n{\n // TODO\n}\n\n//! \\brief Compute the Kronecker product $C = A \\otimes B$. Uses fast remapping tecniques (similar to Matlab reshape)\n//! A,B and x must have dimension n \\times n resp. n*n\n//! \\param[in] A Matrix $n \\times n$\n//! \\param[in] B Matrix $n \\times n$\n//! \\param[in] x Vector of dim $n$\n//! \\param[out] y Vector y = kron(A,B)*x\ntemplate \nvoid kron_super_fast(const Matrix & A, const Matrix & B, const Vector & x, Vector & y)\n{\n // TODO\n}\n\n\nint main(void) {\n \n // Check if kron works, cf. \n Eigen::MatrixXd A(2,2);\n A << 1, 2, 3, 4;\n Eigen::MatrixXd B(2,2);\n B << 5, 6, 7, 8;\n Eigen::MatrixXd C;\n \n Eigen::VectorXd x = Eigen::VectorXd::Random(4);\n Eigen::VectorXd y;\n kron(A,B,C);\n y = C*x;\n std::cout << \"kron(A,B)=\" << std::endl << C << std::endl;\n std::cout << \"Using kron: y= \" << std::endl << y << std::endl;\n \n kron_fast(A,B,x,y);\n std::cout << \"Using kron_fast: y= \" << std::endl << y << std::endl;\n kron_super_fast(A,B,x,y);\n std::cout << \"Using kron_super_fast: y= \" << std::endl << y << std::endl;\n \n // Compute runtime of different implementations of kron\n unsigned int repeats = 10;\n timer<> tm_kron, tm_kron_fast, tm_kron_super_fast;\n std::vector times_kron, times_kron_fast, times_kron_super_fast;\n \n for(unsigned int p = 2; p <= 10; p++) {\n tm_kron.reset();\n tm_kron_fast.reset();\n tm_kron_super_fast.reset();\n for(unsigned int r = 0; r < repeats; ++r) {\n unsigned int M = pow(2,p);\n A = Eigen::MatrixXd::Random(M,M);\n B = Eigen::MatrixXd::Random(M,M);\n x = Eigen::VectorXd::Random(M*M);\n \n // May be too slow for large p, comment if so\n tm_kron.start();\n// kron(A,B,C);\n// y = C*x;\n tm_kron.stop();\n \n tm_kron_fast.start();\n kron_fast(A,B,x,y);\n tm_kron_fast.stop();\n \n tm_kron_super_fast.start();\n kron_super_fast(A,B,x,y);\n tm_kron_super_fast.stop();\n }\n \n std::cout << \"Lazy Kron took: \" << tm_kron.avg().count() / 1000000. << \" ms\" << std::endl;\n std::cout << \"Kron fast took: \" << tm_kron_fast.avg().count() / 1000000. << \" ms\" << std::endl;\n std::cout << \"Kron super fast took: \" << tm_kron_super_fast.avg().count() / 1000000. << \" ms\" << std::endl;\n times_kron.push_back( tm_kron.avg().count() );\n times_kron_fast.push_back( tm_kron_fast.avg().count() );\n times_kron_super_fast.push_back( tm_kron_super_fast.avg().count() );\n }\n \n for(auto it = times_kron.begin(); it != times_kron.end(); ++it) {\n std::cout << *it << \" \";\n }\n std::cout << std::endl;\n for(auto it = times_kron_fast.begin(); it != times_kron_fast.end(); ++it) {\n std::cout << *it << \" \";\n }\n std::cout << std::endl;\n for(auto it = times_kron_super_fast.begin(); it != times_kron_super_fast.end(); ++it) {\n std::cout << *it << \" \";\n }\n std::cout << std::endl;\n}\n", "meta": {"hexsha": "242d09c0657dc7eac39dc078e02b36cd35aefb0c", "size": 3932, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS1/templates/kron.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS1/templates/kron.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS1/templates/kron.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4912280702, "max_line_length": 117, "alphanum_fraction": 0.5579857579, "num_tokens": 1150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.788222135450274}} {"text": "/**\n* Kalman filter header file.\n*\n* @author: Dhruv Shah, Hayk Martirosyan\n* @date: 07/03/2018\n*/\n\n#include \n\n#pragma once\n\nclass KalmanFilter {\n\npublic:\n\n\t/**\n\t* Create a Kalman filter with the specified matrices.\n\t* A - System dynamics matrix\n\t* B - Input matrix\n\t* C - Output matrix\n\t* Q - Process noise covariance\n\t* R - Measurement noise covariance\n\t* P - Estimate error covariance\n\t*/\n\tKalmanFilter(\n\t\t\tconst Eigen::MatrixXd& A,\n\t\t\tconst Eigen::MatrixXd& B,\n\t\t\tconst Eigen::MatrixXd& C,\n\t\t\tconst Eigen::MatrixXd& Q,\n\t\t\tconst Eigen::MatrixXd& R,\n\t\t\tconst Eigen::MatrixXd& P\n\t);\n\n\t/**\n\t* Initialize the filter with initial states as zero.\n\t*/\n\tvoid init();\n\n\t/**\n\t* Initialize the filter with a guess for initial states.\n\t*/\n\tvoid init(const Eigen::VectorXd& x0);\n\n\t/**\n\t* Update the prediction based on control input.\n\t*/\n\tvoid predict(const Eigen::VectorXd& u);\n\n\t/**\n\t* Update the estimated state based on measured values.\n\t*/\n\tvoid update(const Eigen::VectorXd& y);\n\n\t/**\n\t* Update the dynamics matrix.\n\t*/\n\tvoid update_dynamics(const Eigen::MatrixXd A);\n\n\t/**\n\t* Update the output matrix.\n\t*/\n\tvoid update_output(const Eigen::MatrixXd C);\n\n\t/**\n\t* Return the current state.\n\t*/\n\tEigen::VectorXd state() { return x_hat; };\n\nprivate:\n\n\t// Matrices for computation\n\tEigen::MatrixXd A, B, C, Q, R, P, K, P0;\n\n\t// System dimensions\n\tint m, n, c;\n\n\t// Is the filter initialized?\n\tbool initialized = false;\n\n\t// n-size identity\n\tEigen::MatrixXd I;\n\n\t// Estimated states\n\tEigen::VectorXd x_hat;\n};\n", "meta": {"hexsha": "340ffcfb224c289eb6f8dad0665bfa318dacb518", "size": 1524, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/kalman-filter.hpp", "max_stars_repo_name": "PrieureDeSion/kalmanfilter-cpp", "max_stars_repo_head_hexsha": "a30c44ca3c1b386e1badec39ad0830da01bfd1ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-01-02T13:35:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-06T17:28:15.000Z", "max_issues_repo_path": "src/kalman-filter.hpp", "max_issues_repo_name": "PrieureDeSion/kalmanfilter-cpp", "max_issues_repo_head_hexsha": "a30c44ca3c1b386e1badec39ad0830da01bfd1ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kalman-filter.hpp", "max_forks_repo_name": "PrieureDeSion/kalmanfilter-cpp", "max_forks_repo_head_hexsha": "a30c44ca3c1b386e1badec39ad0830da01bfd1ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-23T19:21:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T07:44:22.000Z", "avg_line_length": 17.7209302326, "max_line_length": 57, "alphanum_fraction": 0.6627296588, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285009303773, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7881887339690893}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n\nusing RowMatrixXd = Eigen::Matrix;\n\nEigen::MatrixXd svd(Eigen::Ref mat) {\n Eigen::JacobiSVD svd(mat, Eigen::ComputeThinU | Eigen::ComputeThinV);\n // std::cout << svd.singularValues() << std::endl;\n return svd.matrixU();\n}\n\nEigen::VectorXd lsq(Eigen::Ref mat, Eigen::VectorXd b) {\n Eigen::JacobiSVD svd(mat, Eigen::ComputeThinU | Eigen::ComputeThinV);\n // std::cout << svd.singularValues() << std::endl;\n return svd.solve(b);\n}\n\nEigen::VectorXd ridge(Eigen::Ref mat, Eigen::VectorXd b, double alpha) {\n Eigen::JacobiSVD svd(mat, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n // Get singular values.\n Eigen::VectorXd s = svd.singularValues();\n // std::cout << \"inverse ingular_value:\\n\" << 1.0/s.array() << std::endl;\n\n // Get singular values grater than 1e-15\n Eigen::Matrix indices = (s.array() > 1e-15);\n int survived_singular_value_num = indices.cast().sum();\n Eigen::VectorXd s_nnz = s.topRows(survived_singular_value_num);\n\n // Initialize d matrix which become relaxed inverse singular value vector.\n Eigen::VectorXd d = Eigen::VectorXd::Zero(s.size());\n // relaxed inverse singular value vector d e,g.\n // \t d[idx] = s_nnz / (s_nnz ** 2 + alpha)\n d.head(survived_singular_value_num) = s_nnz.array() / (s_nnz.array().pow(2.0) + alpha).array();\n // std::cout << \"alpha: \" << alpha << \"\\n relaxed inverse siugular values:\\n\" << d << std::endl;\n\n // compute lsq coefficient using psuedo inverse matrix of x.\n return svd.matrixV() * d.asDiagonal() * (svd.matrixU().adjoint()) * b;\n}\n\nnamespace py = pybind11;\nPYBIND11_PLUGIN(_svd_lsq) {\n py::module m(\"_svd_lsq\", \"lsq of svd using eigen and pybind11\");\n\n m.def(\"_svd\", &svd,\n py::return_value_policy::reference_internal,\n \"A function do svd\");\n\n m.def(\"_lsq\", &lsq,\n py::return_value_policy::reference_internal,\n \"solve least square\");\n\n m.def(\"_ridge\", &ridge,\n py::return_value_policy::reference_internal,\n \"ridge\");\n\n return m.ptr();\n\n}\n", "meta": {"hexsha": "cacbfc67c37305aa9dfbf1aa30e3b11bf408bf68", "size": 2351, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/svd_lsq.cpp", "max_stars_repo_name": "SzTk/lsq_using_eigen_pybind11", "max_stars_repo_head_hexsha": "f966b4d297b6286b045443720b8a8a225a8ca32e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cpp/svd_lsq.cpp", "max_issues_repo_name": "SzTk/lsq_using_eigen_pybind11", "max_issues_repo_head_hexsha": "f966b4d297b6286b045443720b8a8a225a8ca32e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/svd_lsq.cpp", "max_forks_repo_name": "SzTk/lsq_using_eigen_pybind11", "max_forks_repo_head_hexsha": "f966b4d297b6286b045443720b8a8a225a8ca32e", "max_forks_repo_licenses": ["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.1692307692, "max_line_length": 100, "alphanum_fraction": 0.6631220757, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7881887313368678}} {"text": "#include \n#include \n#include \n\nusing namespace Eigen;\nusing namespace boost::numeric::odeint;\n\ntemplate \nusing eigen_vector = Matrix;\n\ntypedef eigen_vector<3> state_type;\n\n// System to be solved\nvoid lorenz(const state_type &x, state_type &dxdt, const double &t)\n{\n double sigma = 10.0;\n double R = 28.0;\n double b = 8.0 / 3.0;\n\n dxdt[0] = sigma * (x[1] - x[0]);\n dxdt[1] = R * x[0] - x[1] - x[0] * x[2];\n dxdt[2] = -b * x[2] + x[0] * x[1];\n}\n\n// An example of observer to record steps in the integration\nstruct observer\n{\n std::vector &m_states;\n std::vector &m_times;\n\n observer(std::vector &states, std::vector ×)\n : m_states(states), m_times(times) {}\n\n void operator()(const state_type &x, const double &t)\n {\n m_states.push_back(x);\n m_times.push_back(t);\n }\n};\n\nint main()\n{\n // Defining the state vector with initial conditions\n state_type X;\n X << 0., 1., 0.1;\n\n // Containers to store solution\n std::vector x_sol;\n std::vector times;\n\n // Set custom stepper for Eigen algebra and state\n typedef runge_kutta4 stepper;\n\n // Integrate over time\n auto t_init = 0.0;\n auto t_final = 10.0;\n auto dt = 0.01;\n auto steps = integrate_const(\n stepper(),\n lorenz,\n X,\n t_init,\n t_final,\n dt,\n observer(x_sol, times));\n\n // Displaying result on terminal\n for (size_t i = 0; i <= steps; i++)\n {\n std::cout << times[i] << '\\t' << x_sol[i][0] << '\\t' << x_sol[i][1] << '\\t' << x_sol[i][2] << '\\n';\n }\n\n std::cout << \"\\n*******************\\n\\n\";\n\n // Alternatively, for a finer control, a single step can be done\n X << 0., 1., 0.1;\n std::cout << 0.0 << '\\t' << X[0] << '\\t' << X[1] << '\\t' << X[2] << '\\n';\n for (auto t = t_init; t < t_final; t += dt)\n {\n stepper().do_step(lorenz, X, t, dt);\n std::cout << t << '\\t' << X[0] << '\\t' << X[1] << '\\t' << X[2] << '\\n';\n }\n}\n", "meta": {"hexsha": "0b74f4b7f65de57799bef225f3697010e5f4ed44", "size": 2213, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/boost/standalones/odeint_eigen_example.cpp", "max_stars_repo_name": "volpatto/pysodes", "max_stars_repo_head_hexsha": "48add3ce16ee48e2f3af7a928935f9b22d74d908", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-16T08:28:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T07:29:11.000Z", "max_issues_repo_path": "examples/boost/standalones/odeint_eigen_example.cpp", "max_issues_repo_name": "volpatto/pysodes", "max_issues_repo_head_hexsha": "48add3ce16ee48e2f3af7a928935f9b22d74d908", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/boost/standalones/odeint_eigen_example.cpp", "max_forks_repo_name": "volpatto/pysodes", "max_forks_repo_head_hexsha": "48add3ce16ee48e2f3af7a928935f9b22d74d908", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-09T07:29:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-09T07:29:15.000Z", "avg_line_length": 26.3452380952, "max_line_length": 107, "alphanum_fraction": 0.5616809761, "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896737173119, "lm_q2_score": 0.8558511506439707, "lm_q1q2_score": 0.7880589017520477}} {"text": "/*****************************************************************************\n * deriv.cpp Blitz++ Array example, illustrating expressions,\n * ranges, and subvectors.\n *****************************************************************************/\n\n#include \n\nBZ_USING_NAMESPACE(blitz)\nBZ_USING_NAMESPACE(blitz::tensor)\n\ntypedef Array Array1D;\n\nint main()\n{\n // In this example, the function cos(x)^2 and its second derivative\n // 2 (sin(x)^2 - cos(x)^2) are sampled over the range [0,1).\n // The second derivative is approximated numerically using a\n // [ 1 -2 1 ] mask, and the approximation error is computed.\n\n const int numSamples = 100; // Number of samples\n double delta = 1. / numSamples; // Spacing of samples\n Range R(0, numSamples - 1); // Index set of the vector\n\n // Sample the function y = cos(x)^2 over [0,1)\n //\n // The initialization for y (below) will be translated via expression\n // templates into something of the flavour\n //\n // for (unsigned i=0; i < 99; ++i)\n // {\n // double _t1 = cos(i * delta);\n // y[i] = _t1 * _t1;\n // }\n //\n // The variable i comes from the blitz::tensor namespace, and is\n // an \"index placeholder\" which represents the array index.\n \n Array1D y(R);\n y = sqr(cos(i * delta));\n\n // Sample the exact second derivative\n Array1D y2exact(R);\n y2exact = 2.0 * (sqr(sin(i * delta)) - sqr(cos(i * delta)));\n\n // Approximate the 2nd derivative using a [ 1 -2 1 ] mask\n // We can only apply this mask to the elements 1 .. 98, since\n // we need one element on either side to apply the mask.\n Range I(1,numSamples-2);\n Array1D y2(numSamples);\n\n y2(I) = (y(I-1) - 2 * y(I) + y(I+1)) / (delta*delta);\n \n // The above difference equation will be transformed into\n // something along the lines of\n //\n // double _t2 = delta*delta;\n // for (int i=1; i < 99; ++i)\n // y2[i] = (y[i-1] - 2 * y[i] + y[i+1]) / _t2;\n \n // Now calculate the root mean square approximation error:\n\n double error = sqrt(mean(sqr(y2(I) - y2exact(I))));\n \n // Display a few elements from the vectors.\n // This range constructor means elements 1 to 91 in increments\n // of 15.\n Range displayRange(1, 91, 15);\n \n cout << \"Exact derivative:\" << y2exact(displayRange) << endl\n << \"Approximation: \" << y2(Range(displayRange)) << endl\n << \"RMS Error: \" << error << endl;\n\n return 0;\n}\n\n", "meta": {"hexsha": "099d8599f6caf467cea1ac3f702658e933041832", "size": 2543, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/examples/deriv.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/examples/deriv.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/examples/deriv.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4605263158, "max_line_length": 79, "alphanum_fraction": 0.5536767597, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836382, "lm_q2_score": 0.8705972667296309, "lm_q1q2_score": 0.7875862921564654}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::cout;\nusing std::endl;\nusing std::ofstream;\nusing std::pow; \nusing std::default_random_engine;\nusing std::normal_distribution;\nusing std::bind;\n\ndefault_random_engine re{12345};\nnormal_distribution norm(0, 1);\nauto rnorm = bind(norm, re);\n\ndouble func(double x){\n return 3*x*x-7*x+2;\n}\nint main() \n{\n using namespace Eigen;\n using namespace std;\n \n VectorXd x = VectorXd::LinSpaced(10, 10, 15);\n VectorXd y(10);\n for (int i=0; i<10; i++) {\n y(i) = func(x(i)) + 10*rnorm();\n }\n cout << \"10 x-coordinates: \"<< x.transpose() << \"\\n\\n\";\n cout << \"10 y-coordinates: \"<< y.transpose() << \"\\n\\n\";\n cout << \"The distance is: \" << sqrt((x-y).transpose()*(x-y))<< endl;\n \n double cov = (x.rowwise() - x.colwise().mean()).transpose()*(y.rowwise() - y.colwise().mean());\n double x_norm_sq = (x.rowwise() - x.colwise().mean()).transpose()*(x.rowwise() - x.colwise().mean());\n double y_norm_sq = (y.rowwise() - y.colwise().mean()).transpose()*(y.rowwise() - y.colwise().mean());\n double corr = cov / sqrt(x_norm_sq * y_norm_sq);\n cout << \"The correlation is: \" << corr << endl;\n \n int m = 10, n = 3;\n VectorXf coeff(n), b(m);\n MatrixXf A(m,n);\n for(int i=0; i\n#include \n#include \"HermitePolynomials.h\"\n\n/**\n * Calcul du polynôme Hermite par recurrence\n *\n * Cette fonction a pour but d'Calculation du polynôme Hermite par recurrence\n *\n * @param n\n * @param z\n *\n * @return la valeur de la fonction Hn(z)\n */\ndouble HermitePolynomials::calculateHermite(int n, double z)\n{\n if (n == 0)\n return 1;\n else if (n == 1)\n return (2*z);\n else\n return (2 * z * calculateHermite(n-1, z) - 2 * (n-1) * calculateHermite(n-2, z));\n}\n\n\n\n/**\n * Calcul du polynôme d'Hermite par récurrence\n *\n * Cette fonction a pour but de calculer le polynôme d'Hermite par récurrence avec des vecteurs\n *\n * @param n\n * @param Z un vecteur de valeurs\n *\n * @return un vecteur contenant les valeurs de la fonction Hermite Hn(z)\n */\narma::mat HermitePolynomials::calculateHermite(int n, arma::mat Z)\n{\n if (n == 0)\n {\n arma::mat A = Z.ones(size(Z));\n return A;\n }\n else\n {\n if (n == 1)\n {\n return Z.for_each([](arma::mat::elem_type& val)\n {\n val = 2 * val;\n });\n }\n else\n {\n return (2 * (Z % calculateHermite(n - 1, Z))) - (2 * (n-1) * calculateHermite(n - 2, Z));\n }\n }\n}\n\n\n\n", "meta": {"hexsha": "e82b4651fb5c1ad56d5b0dbaea9fa1207177a028", "size": 1389, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/HermitePolynomials.cpp", "max_stars_repo_name": "DinghaoLI/SchrodingerEquation", "max_stars_repo_head_hexsha": "1dc139b5ca33506e28de7e4a9c966e86f3c2078b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HermitePolynomials.cpp", "max_issues_repo_name": "DinghaoLI/SchrodingerEquation", "max_issues_repo_head_hexsha": "1dc139b5ca33506e28de7e4a9c966e86f3c2078b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HermitePolynomials.cpp", "max_forks_repo_name": "DinghaoLI/SchrodingerEquation", "max_forks_repo_head_hexsha": "1dc139b5ca33506e28de7e4a9c966e86f3c2078b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4264705882, "max_line_length": 101, "alphanum_fraction": 0.5680345572, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.853912760387131, "lm_q1q2_score": 0.7872408243577607}} {"text": "#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n cout.precision(3);\n ArrayXXf table(10, 4);\ntable.col(0) = ArrayXf::LinSpaced(10, 0, 90);\ntable.col(1) = M_PI / 180 * table.col(0);\ntable.col(2) = table.col(1).sin();\ntable.col(3) = table.col(1).cos();\nstd::cout << \" Degrees Radians Sine Cosine\\n\";\nstd::cout << table << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "e13e1c3564d9fa4333ed86c53757f06b01c6459c", "size": 423, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tutorial_AdvancedInitialization_LinSpaced.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_Tutorial_AdvancedInitialization_LinSpaced.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_Tutorial_AdvancedInitialization_LinSpaced.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": 21.15, "max_line_length": 57, "alphanum_fraction": 0.6312056738, "num_tokens": 142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7870771226480798}} {"text": "#include \n#include \n\n\n\nvoid create_plane(long double xmin, long double xmax, int xlen, long double ymin, long double ymax, int ylen);\n\n\n\n\n\nint main(int argc, char **argv) \n{\n // exploit namespaces to shorten code\n using namespace boost::numeric::ublas;\n using std::cout; \n using std::endl;\n\n create_plane(0,10,3,0,10,3);\n \n // declare three 3x3 matrices of complex elements\n matrix > m(3, 3), n(3, 3), o(3, 3);\n\n // iterate over 3x3 matrix entries\n // r : row index\n // c : column index\n for (unsigned r = 0; r < m.size1(); r++) {\n for (unsigned c = 0; c < m.size2(); c++) {\n // enumerated matrix entries\n m(r,c) = 3 * r + c;\n\n // complex numbers designating rows and cols\n n(r,c) = r + c * std::complex(0,1); \n\n // elementwise square of n\n o(r,c) = std::pow(n(r,c), 2);\n }\n }\n \n // print to screen as demonstration\n cout << \"m:\" << endl;\n cout << m << endl;\n cout << endl << \"n:\" << endl;\n cout << n << endl;\n cout << endl << \"o:\" << endl;\n cout << n << endl;\n cout << endl << \"m + n:\" << endl;\n cout << m + n << endl;\n cout << endl << \"m * n:\" << endl;\n cout << prod(m, n) << endl;\n cout << endl << \"n * n - o:\" << endl;\n cout << prod(n, n) - o << endl;\n}\n\nvoid create_plane(long double xmin, long double xmax, int xlen, long double ymin, long double ymax, int ylen) {\n \n using namespace boost::numeric::ublas;\n using std::cout;\n using std::endl;\n \n long double dx = (xmax-xmin)/(xlen-1);\n long double dy = (ymax-ymin)/(ylen-1);\n \n matrix > cplane(xlen, ylen);\n \n for (unsigned r = 0; r < cplane.size1(); r++) {\n for (unsigned c = 0; c < cplane.size2(); c++) {\n \n cplane(r,c) =std::complex(xmin + c*dy, ymin + r*dy);\n \n }\n }\n\n for (unsigned int i=0; i\n#include \nusing namespace std;\n\n#include \n#include \n\nusing namespace Eigen;\n\n/**************************************************\n * A demo for the Geometry module in Eigen\n * including roatation matrix, quarternion and euler number\n * to install Eigen, use: sudo apt-get install libeigen3-dev\n * Official documentation: https://eigen.tuxfamily.org/dox/group__TutorialGeometry.html\n * *************************************************/\n\nint main(int argc, char **argv) {\n // Different ways to represent Rotations and Translations\n // 1. 3d rotation matrix\n Matrix3d rotation_matrix = Matrix3d::Identity(); // initialized to Identity matrix\n\n // 2. Roatation vector: AngleAxis\n // The bottom is not a matrix, but it supports matrix operations through overloading\n AngleAxisd rotation_vector(M_PI / 4, Vector3d(0, 0, 1)); // rotate 45 degree on z axis\n cout.precision(3);\n cout << \"rotation matrix = \\n\" << rotation_vector.matrix() << endl; // use .matrix() to convert it into a matrix\n // can also use .toRotationMatrix() and assign it to a matrix\n rotation_matrix = rotation_vector.toRotationMatrix();\n\n // Use AngleAxis to do coordinate transformation, just use *\n Vector3d v(1, 0, 0); // the vector to be rotated\n Vector3d v_rotated = rotation_vector * v;\n cout << \"(1, 0, 0) after rotation (by angle axis) = \" << v_rotated.transpose() << endl;\n // Use rotation matrix to do coordinate transformation\n v_rotated = rotation_matrix * v;\n cout << \"(1, 0, 0) after rotation (by matrix) = \" << v_rotated.transpose() << endl;\n\n // 3. Euler angle\n // We can transfer rotation matrix into Euler angle directly, through .eulerAngles(2, 1, 0)\n Vector3d euler_angles = rotation_matrix.eulerAngles(2, 1, 0); // ZYX, i.e. roll, pitch, yaw\n cout << \"yaw pitch roll = \" << euler_angles.transpose() << endl;\n\n // 4. Euclidean transform matrix (rotation + translation): Eigen::Isometry\n Isometry3d T = Isometry3d::Identity(); // 4*4 matrix\n T.rotate(rotation_vector); // rotate according to rotation vector\n T.pretranslate(Vector3d(1, 3, 4)); // Set the translation vector as (1, 3, 4)\n cout << \"Transform matrix = \\n\" << T.matrix() << endl;\n\n // use the transform matrix to do transformation: left-multiply it\n Vector3d v_transformed = T * v; // same as: R * v + t\n cout << \"v transformed = \" << v_transformed.transpose() << endl;\n\n // For affine transform, use Eigen::Affine3d\n // For Projective transform, use Eigen::Projective3d\n\n\n // 5. Quaternion\n // can initalize quaternion through AngleAxis, and vice versa\n Quaterniond q = Quaterniond(rotation_vector);\n // q.coeffs() returns (x, y, z, w), where w is the real part\n cout << \"quaternion from rotation vector = \" << q.coeffs().transpose() << endl;\n // can also assign the roation matrix to it\n q = Quaterniond(rotation_matrix);\n cout << \"quaternion from rotation matrix = \" << q.coeffs().transpose() << endl;\n\n // Use the overloaded * to rotate a vector through quaternion\n v_rotated = q * v; // Actually, is qvq^{-1} in mathematical\n cout << \"(1,0,0) after rotation = \" << v_rotated.transpose() << endl;\n // Can also use qvq^{-1} to do the rotation\n cout << \"it's equivalent to: \" << (q * Quaterniond(0, 1, 0, 0) * q.inverse()).coeffs().transpose() << endl; \n\n return 0;\n \n // For reference: Different types of transformation matrices\n // Rotation matrix (3 * 3): Eigen::Matrix3d\n // Rotation vector (3 * 1): Eigen::AngleAxisd\n // Euler angle (3 * 1): Eigen::Vector3d\n // Quaternion (4 * 1): Eigen::Quaterniond\n // Euclidean transformation matrix (4 * 4): Eigen::Isometry3d\n // Affine transform (4 * 4): Eigen::Affine3d\n // Perspective transformation (4 * 4): Eigen::Projective3d\n\n\n}\n\n\n\n\n\n", "meta": {"hexsha": "28c40b7766b4e4da28f1035a7787372e9ba9128b", "size": 3925, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/useGeometry/eigenGeometry.cpp", "max_stars_repo_name": "henryxuy/slam-codeInBook-en", "max_stars_repo_head_hexsha": "ec3c8ec8d5facfdeb0832be121de105cea73790b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch3/useGeometry/eigenGeometry.cpp", "max_issues_repo_name": "henryxuy/slam-codeInBook-en", "max_issues_repo_head_hexsha": "ec3c8ec8d5facfdeb0832be121de105cea73790b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch3/useGeometry/eigenGeometry.cpp", "max_forks_repo_name": "henryxuy/slam-codeInBook-en", "max_forks_repo_head_hexsha": "ec3c8ec8d5facfdeb0832be121de105cea73790b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.6111111111, "max_line_length": 117, "alphanum_fraction": 0.6379617834, "num_tokens": 1040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.7867572435423188}} {"text": "/**\n * @file transformations.cpp\n * @brief Convenience transformation matrices written in 3D homogeneous coordinates (i.e. matrices shape is 4x4).\n * Under the hood, Eigen matrices are used.\n * \n * @author Daniel Calderón\n * @license MIT\n*/\n\n#include \"transformations.h\"\n\n#include \n#include \n\nnamespace Grafica\n{\nnamespace Transformations\n{\n\nMatrix4f identity()\n{\n return Matrix4f::Identity();\n}\n\nMatrix4f uniformScale(Coord s)\n{\n return (Matrix4f() <<\n s, 0, 0, 0,\n 0, s, 0, 0,\n 0, 0, s, 0,\n 0, 0, 0, 1).finished();\n}\n\nMatrix4f scale(Coord sx, Coord sy, Coord sz)\n{\n return (Matrix4f() <<\n sx, 0, 0, 0,\n 0, sy, 0, 0,\n 0, 0, sz, 0,\n 0, 0, 0, 1).finished();\n}\n\nMatrix4f rotationX(Coord theta_radians)\n{\n Coord sin_theta = std::sin(theta_radians);\n Coord cos_theta = std::cos(theta_radians);\n\n return (Matrix4f() <<\n 1, 0, 0, 0,\n 0, cos_theta, -sin_theta, 0,\n 0, sin_theta, cos_theta, 0,\n 0, 0, 0, 1).finished();\n}\n\nMatrix4f rotationY(Coord theta_radians)\n{\n Coord sin_theta = std::sin(theta_radians);\n Coord cos_theta = std::cos(theta_radians);\n\n return (Matrix4f() <<\n cos_theta, 0, sin_theta, 0,\n 0, 1, 0, 0,\n -sin_theta, 0, cos_theta, 0,\n 0, 0, 0, 1).finished();\n}\n\nMatrix4f rotationZ(Coord theta_radians)\n{\n Coord sin_theta = std::sin(theta_radians);\n Coord cos_theta = std::cos(theta_radians);\n\n return (Matrix4f() <<\n cos_theta, -sin_theta, 0, 0,\n sin_theta, cos_theta, 0, 0,\n 0, 0, 1, 0,\n 0, 0, 0, 1).finished();\n}\n\nMatrix4f rotationA(Coord theta_radians, Vector3f axis)\n{\n Coord s = std::sin(theta_radians);\n Coord c = std::cos(theta_radians);\n\n axis.normalize();\n\n Coord x = axis[0];\n Coord y = axis[1];\n Coord z = axis[2];\n\n return (Matrix4f() <<\n // First row\n c + (1 - c) * x * x,\n (1 - c) * x * y - s * z,\n (1 - c) * x * z + s * y,\n 0,\n // Second row\n (1 - c) * x * y + s * z,\n c + (1 - c) * y * y,\n (1 - c) * y * z - s * x,\n 0,\n // Third row\n (1 - c) * x * z - s * y,\n (1 - c) * y * z + s * x,\n c + (1 - c) * z * z,\n 0,\n // Fourth row\n 0,0,0,1).finished();\n}\n\nMatrix4f translate(Coord tx, Coord ty, Coord tz)\n{\n return (Matrix4f() <<\n 1, 0, 0, tx,\n 0, 1, 0, ty,\n 0, 0, 1, tz,\n 0, 0, 0, 1).finished();\n}\n\nMatrix4f shearing(Coord xy, Coord yx, Coord xz, Coord zx, Coord yz, Coord zy)\n{\n return (Matrix4f() <<\n 1, xy, xz, 0,\n yx, 1, yz, 0,\n zx, zy, 1, 0,\n 0, 0, 0, 1).finished();\n}\n\nMatrix4f frustum(Coord left, Coord right, Coord bottom, Coord top, Coord near, Coord far)\n{\n Coord r_l = right - left;\n Coord t_b = top - bottom;\n Coord f_n = far - near;\n\n return (Matrix4f() <<\n // First row\n 2 * near / r_l,\n 0,\n (right + left) / r_l,\n 0,\n // Second row\n 0,\n 2 * near / t_b,\n (top + bottom) / t_b,\n 0,\n // Third row\n 0,\n 0,\n -(far + near) / f_n,\n -2 * near * far / f_n,\n // Fourth row\n 0, 0, -1, 0).finished();\n}\n\nMatrix4f perspective(Coord fovy, Coord aspect, Coord near, Coord far)\n{\n Coord halfHeight = std::tan(M_PI * fovy / 360) * near;\n Coord halfWidth = halfHeight * aspect;\n\n return frustum(-halfWidth, halfWidth, -halfHeight, halfHeight, near, far);\n}\n\n\nMatrix4f ortho(Coord left, Coord right, Coord bottom, Coord top, Coord near, Coord far)\n{\n Coord r_l = right - left;\n Coord t_b = top - bottom;\n Coord f_n = far - near;\n\n return (Matrix4f() <<\n // First row\n 2 / r_l,\n 0,\n 0,\n -(right + left) / r_l,\n // Second row\n 0,\n 2 / t_b,\n 0,\n -(top + bottom) / t_b,\n // Third row\n 0,\n 0,\n -2 / f_n,\n -(far + near) / f_n,\n // Fourth row\n 0, 0, 0, 1).finished();\n}\n\n\nMatrix4f lookAt(Vector3f const& eye, Vector3f const& at, Vector3f const& up)\n{\n Vector3f forward = at - eye;\n forward.normalize();\n\n Vector3f side = forward.cross(up);\n side.normalize();\n\n Vector3f newUp = side.cross(forward);\n newUp.normalize();\n\n return (Matrix4f() <<\n side[0], side[1], side[2], -side.dot(eye),\n newUp[0], newUp[1], newUp[2], -newUp.dot(eye),\n -forward[0], -forward[1], -forward[2], forward.dot(eye),\n 0,0,0,1).finished();\n}\n\n} // Transformations\n} // Grafica", "meta": {"hexsha": "6421fbe8207b6b088a811bcb5f5a93b4a4f3c96d", "size": 4729, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/grafica/transformations.cpp", "max_stars_repo_name": "alec280/qdu-engine", "max_stars_repo_head_hexsha": "f1bf1be25c6dcfdd0ca182e58419b8b486149c60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-26T03:53:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:53:03.000Z", "max_issues_repo_path": "source/grafica/transformations.cpp", "max_issues_repo_name": "alec280/qdu-engine", "max_issues_repo_head_hexsha": "f1bf1be25c6dcfdd0ca182e58419b8b486149c60", "max_issues_repo_licenses": ["MIT"], "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/grafica/transformations.cpp", "max_forks_repo_name": "alec280/qdu-engine", "max_forks_repo_head_hexsha": "f1bf1be25c6dcfdd0ca182e58419b8b486149c60", "max_forks_repo_licenses": ["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.6267942584, "max_line_length": 113, "alphanum_fraction": 0.5011630366, "num_tokens": 1564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422186079558, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.786320483870444}} {"text": "#include \n#include \n#include \n#include \n#include \"sophus/se3.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\n\nint main(){\n Matrix3d R = AngleAxisd(M_PI/2, Vector3d(0,0,1)).toRotationMatrix();\n Quaterniond q(R);\n Sophus::SO3d SO3_R(R);\n Sophus::SO3d SO3_q(q);\n\n cout << \"SO3 from matrix: \\n\" << SO3_R.matrix() << endl;\n cout << \"SO3 from quaternion: \\n\" << SO3_q.matrix() << endl;\n\n Vector3d so3 = SO3_R.log();\n cout << \"so3 = \" << so3.transpose() << endl;\n cout << \"so3 hat = \\n\" << Sophus::SO3d::hat(so3) << endl;\n cout << \"so3 hat vee = \" << Sophus::SO3d::vee(Sophus::SO3d::hat(so3)).transpose() << endl;\n\n Vector3d update_so3(1e-4,0,0);\n Sophus::SO3d SO3_updated = Sophus::SO3d::exp(update_so3)*SO3_R;\n cout << \"SO3 updated = \\n\" << SO3_updated.matrix();\n\n cout << \"------------------------------------------\" << endl;\n\n Vector3d t(1,0,0);\n Sophus::SE3d SE3R_t(R,t);\n Sophus::SE3d SE3q_t(q,t);\n cout << \"SE3 from R,t = \\n\" << SE3R_t.matrix() << endl;\n cout << \"SE3 from q,t = \\n\" << SE3q_t.matrix() << endl;\n\n Eigen::Matrix se3 = SE3R_t.log();\n cout << \"se3 = \" << se3.transpose() << endl;\n\n cout << \"se3 hat = \\n\" << Sophus::SE3d::hat(se3) << endl;\n cout << \"se3 hat vee = \" << Sophus::SE3d::vee(Sophus::SE3d::hat(se3)).transpose() << endl;\n\n Eigen::Matrix se3_update;\n se3_update << 1e-4,0,0,0,0,0;\n Sophus::SE3d SE3_updated = Sophus::SE3d::exp(se3_update)*SE3R_t;\n cout << \"SE3 updated = \\n\" << SE3_updated.matrix() << endl;\n\n}", "meta": {"hexsha": "b58c23fdb86cac3da8123e45abbcc503d4119a42", "size": 1585, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch4/testSophus.cpp", "max_stars_repo_name": "LeoDuhz/learn_slambook", "max_stars_repo_head_hexsha": "39be3fc667b0481ff6297b6add0c456c8f6e98c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch4/testSophus.cpp", "max_issues_repo_name": "LeoDuhz/learn_slambook", "max_issues_repo_head_hexsha": "39be3fc667b0481ff6297b6add0c456c8f6e98c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch4/testSophus.cpp", "max_forks_repo_name": "LeoDuhz/learn_slambook", "max_forks_repo_head_hexsha": "39be3fc667b0481ff6297b6add0c456c8f6e98c8", "max_forks_repo_licenses": ["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.7234042553, "max_line_length": 94, "alphanum_fraction": 0.5753943218, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7862530734661131}} {"text": "#include \n#include \n#include \n#include \n#include \"sophus/se3.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\n\n/// 本程序演示sophus的基本用法\n\nint main(int argc, char **argv) {\n\n // 沿Z轴转90度的旋转矩阵\n Matrix3d R = AngleAxisd(M_PI / 2, Vector3d(0, 0, 1)).toRotationMatrix();\n // 或者四元数\n Quaterniond q(R);\n Sophus::SO3d SO3_R(R); // Sophus::SO3d可以直接从旋转矩阵构造\n Sophus::SO3d SO3_q(q); // 也可以通过四元数构造\n // 二者是等价的\n cout << \"SO(3) from matrix:\\n\" << SO3_R.matrix() << endl;\n cout << \"SO(3) from quaternion:\\n\" << SO3_q.matrix() << endl;\n cout << \"they are equal\" << endl;\n\n // 使用对数映射获得它的李代数\n Vector3d so3 = SO3_R.log();\n cout << \"so3 = \" << so3.transpose() << endl;\n // hat 为向量到反对称矩阵\n cout << \"so3 hat=\\n\" << Sophus::SO3d::hat(so3) << endl;\n // 相对的,vee为反对称到向量\n cout << \"so3 hat vee= \" << Sophus::SO3d::vee(Sophus::SO3d::hat(so3)).transpose() << endl;\n\n // 增量扰动模型的更新\n Vector3d update_so3(1e-4, 0, 0); //假设更新量为这么多\n Sophus::SO3d SO3_updated = Sophus::SO3d::exp(update_so3) * SO3_R;\n cout << \"SO3 updated = \\n\" << SO3_updated.matrix() << endl;\n\n cout << \"*******************************\" << endl;\n // 对SE(3)操作大同小异\n Vector3d t(1, 0, 0); // 沿X轴平移1\n Sophus::SE3d SE3_Rt(R, t); // 从R,t构造SE(3)\n Sophus::SE3d SE3_qt(q, t); // 从q,t构造SE(3)\n cout << \"SE3 from R,t= \\n\" << SE3_Rt.matrix() << endl;\n cout << \"SE3 from q,t= \\n\" << SE3_qt.matrix() << endl;\n // 李代数se(3) 是一个六维向量,方便起见先typedef一下\n typedef Eigen::Matrix Vector6d;\n Vector6d se3 = SE3_Rt.log();\n cout << \"se3 = \" << se3.transpose() << endl;\n // 观察输出,会发现在Sophus中,se(3)的平移在前,旋转在后.\n // 同样的,有hat和vee两个算符\n cout << \"se3 hat = \\n\" << Sophus::SE3d::hat(se3) << endl;\n cout << \"se3 hat vee = \" << Sophus::SE3d::vee(Sophus::SE3d::hat(se3)).transpose() << endl;\n\n // 最后,演示一下更新\n Vector6d update_se3; //更新量\n update_se3.setZero();\n update_se3(0, 0) = 1e-4d;\n Sophus::SE3d SE3_updated = Sophus::SE3d::exp(update_se3) * SE3_Rt;\n cout << \"SE3 updated = \" << endl << SE3_updated.matrix() << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "86cae57d0184f16531afdf5f2bf871f8d6235120", "size": 2070, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch4/useSophus.cpp", "max_stars_repo_name": "GinkgoX/slam_14_chapters", "max_stars_repo_head_hexsha": "bfa764344b3a2e6171bceae26237be6c4eeb350c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch4/useSophus.cpp", "max_issues_repo_name": "GinkgoX/slam_14_chapters", "max_issues_repo_head_hexsha": "bfa764344b3a2e6171bceae26237be6c4eeb350c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch4/useSophus.cpp", "max_forks_repo_name": "GinkgoX/slam_14_chapters", "max_forks_repo_head_hexsha": "bfa764344b3a2e6171bceae26237be6c4eeb350c", "max_forks_repo_licenses": ["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.8571428571, "max_line_length": 92, "alphanum_fraction": 0.5922705314, "num_tokens": 930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897426182321, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7860143360526022}} {"text": "#ifndef R_1_PUBLIC_GRAPH_SPECTRAL_H_\n#define R_1_PUBLIC_GRAPH_SPECTRAL_H_\n\n#include \n#include \"Graph.hpp\"\n\n#include \n\nnamespace R1 {\n\tclass SpectralGraph : public Graph {\n\tpublic:\n\t\tvirtual ~SpectralGraph() {}\n\n\t\tSpectralGraph(int NVertex) : Graph(NVertex) {\n\n\t\t}\n\n\t\tSpectralGraph() {\n\n\t\t}\n\n\t\t//\n\t\t// spectral graph properties\n\t\t//\n\n\t\tEigen::VectorXf spectrum() {\n\t\t\tEigen::SelfAdjointEigenSolver eg1(adjacency_matrix);\n\t\t\treturn eg1.eigenvalues();\n\t\t}\n\n\t\t// The energy of G was first defined by Gutman in 1978 as \n\t\t// the sum of the absolute values of its eigenvalues\n\t\tdouble energy() {\n\t\t\tEigen::MatrixXf::EigenvaluesReturnType eg = adjacency_matrix.eigenvalues();\n\t\t\tdouble energySum = 0;\n\n\t\t\tfor (int i = 0; i < eg.rows(); i++)\t{\n\t\t\t\tfor (int j = 0; j < eg.cols(); j++)\t{\n\t\t\t\t\tenergySum += sqrt(pow(eg(i, j).real(), 2) + pow(eg(i, j).imag(), 2));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn energySum;\n\t\t}\n\n\t\t// Two graphs are called isospectral or cospectral if the\n\t\t// adjacency matrices of the graphs have equal multisets\n\t\t// of eigenvalues.\n\t\tstatic bool isospectral(SpectralGraph g1, SpectralGraph g2)\n\t\t{\n\t\t\treturn g1.spectrum() == g2.spectrum();\n\t\t}\n\n\t\t// Two graphs are called isospectral or cospectral if the\n\t\t// adjacency matrices of the graphs have equal multisets\n\t\t// of eigenvalues.\n\t\tstatic bool isospectral(SpectralGraph g1, SpectralGraph g2, double epsilon)\t{\n\t\t\tEigen::SelfAdjointEigenSolver eg1(g1.adjacency_matrix);\n\t\t\tEigen::SelfAdjointEigenSolver eg2(g2.adjacency_matrix);\n\n\t\t\tif (eg1.info() != Eigen::Success) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (eg2.info() != Eigen::Success) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tEigen::VectorXf normalizedEg1 = eg1.eigenvalues().normalized();\n\t\t\tEigen::VectorXf normalizedEg2 = eg2.eigenvalues().normalized();\t\n\n\t\t\tif (normalizedEg1.cols() != normalizedEg2.cols()) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (normalizedEg1.rows() != normalizedEg2.rows()) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < normalizedEg1.rows(); i++)\t{\n\t\t\t\tfor (int j = 0; j < normalizedEg1.cols(); j++)\t{\n\t\t\t\t\tif (abs(normalizedEg1(i, j) - normalizedEg2(i, j)) > epsilon) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\t//////////////////////////////////////////////////////////////////////////\n\t\t//\t\t\t\t\t\t\t\tLaplacian\n\t\t//////////////////////////////////////////////////////////////////////////\n\n\t\tfloat laplacian(int u, int v) {\n\n\t\t\tfloat du = degree(u);\n\n\t\t\tif (u == v && du != 0) {\n\t\t\t\treturn du;\n\t\t\t} else if (adjacency_matrix(u, v) > 0.0f) {\n\t\t\t\treturn -adjacency_matrix(u, v);\n\t\t\t}\n\n\t\t\treturn 0.0f;\n\t\t}\n\n\n\t\tfloat normalizedLaplacian(int u, int v) {\n\n\t\t\tfloat du = degree(u);\n\n\t\t\tif (u == v && du != 0) {\n\t\t\t\treturn 1.0;\n\t\t\t}\n\t\t\telse if (adjacency_matrix(u, v) > 0.0) {\n\n\t\t\t\tfloat dv = degree(v);\n\n\t\t\t\treturn -adjacency_matrix(u, v) / sqrt(du * dv);\n\t\t\t}\n\n\t\t\treturn 0.0f;\n\t\t}\n\n\t\tEigen::MatrixXf getLaplacianMatrix() {\n\t\t\tEigen::MatrixXf degree_matrix(n_vertex, n_vertex);\n\t\t\tdegree_matrix.setZero();\n\n\t\t\tfor (int i = 0; i < n_vertex; i++)\t{\n\t\t\t\tdegree_matrix(i, i) = degree(i);\n\t\t\t}\n\n\t\t\treturn degree_matrix - adjacency_matrix;\n\t\t}\n\n\t\tEigen::MatrixXf getAjacencyMatrix() {\n\t\t\treturn adjacency_matrix;\n\t\t}\n\t\t\n\n\t\tEigen::MatrixXf getLaplacianMatrix_obsolete() {\n\t\t\tEigen::MatrixXf laplacian_matrix(n_vertex, n_vertex);\n\n\t\t\tfor (int i = 0; i < n_vertex; i++)\t{\n\t\t\t\tfor (int j = 0; j < n_vertex; j++)\t{\n\t\t\t\t\tlaplacian_matrix(i, j) = laplacian(i, j);\n\t\t\t\t}\n\n\t\t\t\tif (n_vertex > 10 && (i % (n_vertex / 10) == 0))\n\t\t\t\t\tstd::cout << \"LAPLACIAN : \" << (100 * i) / n_vertex << std::endl;\n\t\t\t}\n\n\t\t\treturn laplacian_matrix;\n\t\t}\n\n\t\tEigen::MatrixXf getNormalizedLaplacianMatrix() {\n\t\t\tEigen::MatrixXf degree_matrix(n_vertex, n_vertex);\n\t\t\tdegree_matrix.setZero();\n\n\t\t\tfor (int i = 0; i < n_vertex; i++)\t{\n\t\t\t\tdegree_matrix(i, i) = 1.0f / (sqrt(degree(i)));\n\t\t\t}\n\t\t\t\n\t\t\treturn Eigen::MatrixXf::Identity(n_vertex, n_vertex) - degree_matrix * adjacency_matrix * degree_matrix;\n\t\t}\n\n\t\tEigen::MatrixXf getNormalizedLaplacianMatrix_obsolete() {\n\t\t\tEigen::MatrixXf laplacian_matrix(n_vertex, n_vertex);\n\n\t\t\tfor (int i = 0; i < n_vertex; i++)\t{\n\t\t\t\tfor (int j = 0; j < n_vertex; j++)\t{\n\t\t\t\t\tlaplacian_matrix(i, j) = normalizedLaplacian(i, j);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn laplacian_matrix;\n\t\t}\n\n\t\tEigen::VectorXcf laplacianSpectrum() {\n\n\t\t\tEigen::MatrixXf L = getLaplacianMatrix();\n\t\t\tEigen::EigenSolver eg1(L);\n\t\t\treturn eg1.eigenvalues();\n\t\t}\n\n\t\tEigen::VectorXcf normalizedLaplacianSpectrum() {\n\n\t\t\tEigen::MatrixXf L = getLaplacianMatrix();\n\t\t\tEigen::EigenSolver eg1(L);\n\t\t\treturn eg1.eigenvalues();\n\t\t}\n\n\t\tEigen::MatrixXcf laplacianEigenVectors() {\n\n\t\t\tEigen::MatrixXf L = getLaplacianMatrix();\n\n\t\t\tEigen::EigenSolver eg1(L);\n\t\t\treturn eg1.eigenvectors();\n\t\t}\n\n\t\tEigen::MatrixXcf normalizedLaplacianEigenVectors() {\n\n\t\t\tEigen::MatrixXf L = getNormalizedLaplacianMatrix();\n\n\t\t\tEigen::EigenSolver eg1(L);\n\t\t\treturn eg1.eigenvectors();\n\t\t}\n\n\t\t// The Fiedler vector of the graph Laplacian\n\t\tEigen::VectorXf getFiedlerVector(bool normalize = false) {\n\n\t\t\tEigen::MatrixXf L;\n\t\t\tif (!normalize)\n\t\t\t\tL = getLaplacianMatrix();\n\t\t\telse\n\t\t\t\tL = getNormalizedLaplacianMatrix();\n\n\t\t\tEigen::SelfAdjointEigenSolver eg1;\n\t\t\teg1.compute(L, Eigen::DecompositionOptions::ComputeEigenvectors);\n\n\t\t\tEigen::VectorXf spec = eg1.eigenvalues();\n\n\t\t\tstd::cout << spec << std::endl;\n\n\t\t\tfloat m0 = FLT_MAX;\n\t\t\tfloat m1 = FLT_MAX;\n\n\t\t\tint m0_index = 0;\n\t\t\tint m1_index = 0;\n\n\t\t\tfor (int i = 0; i < spec.size(); i++)\n\t\t\t{\n\t\t\t\tif (spec(i) < m0)\n\t\t\t\t{\n\t\t\t\t\tm0 = spec(i);\n\t\t\t\t\tm0_index = i;\n\t\t\t\t}\n\t\t\t\telse if (spec(i) <= m1) \n\t\t\t\t{\n\t\t\t\t\tm1 = spec(i);\n\t\t\t\t\tm1_index = i;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn eg1.eigenvectors().col(m1_index);\n\t\t}\n\n\t\tvoid getSortedFiedlerVector(std::vector& fiedlerVector, bool normalize = false)\n\t\t{\n\t\t\tEigen::VectorXf fv = getFiedlerVector(normalize);\n\n\t\t\tfor (int i = 0; i < fv.size(); i++)\n\t\t\t{\n\t\t\t\tfiedlerVector.push_back(fv(i));\n\t\t\t}\n\t\t\t\n\t\t\tstd::sort(fiedlerVector.begin(), fiedlerVector.end());\n\t\t}\n\n\t\tstatic float FiedlerVectorSimilarity(SpectralGraph& sg1, SpectralGraph& sg2)\n\t\t{\n\t\t\tstd::vector fiedlerVector1;\n\t\t\tstd::vector fiedlerVector2;\n\n\t\t\tsg1.getSortedFiedlerVector(fiedlerVector1);\n\t\t\tsg2.getSortedFiedlerVector(fiedlerVector2);\n\n\t\t\tsize_t n = std::max(fiedlerVector1.size(), fiedlerVector2.size());\n\n\t\t\tEigen::VectorXf fv1(n);\n\t\t\tEigen::VectorXf fv2(n);\n\n\t\t\tfv1.setZero();\n\t\t\tfv2.setZero();\n\n\t\t\tfor (size_t i = 0; i < n; i++)\n\t\t\t{\n\t\t\t\tif (i < fiedlerVector1.size())\n\t\t\t\t{\n\t\t\t\t\tfv1(i) = fiedlerVector1[i];\n\t\t\t\t}\n\n\t\t\t\tif (i < fiedlerVector2.size())\n\t\t\t\t{\n\t\t\t\t\tfv2(i) = fiedlerVector2[i];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn fv1.dot(fv2) / (fv1.norm() * fv2.norm());\n\t\t}\n\n\t\tvoid saveDotFile(std::string filename)\n\t\t{\n\t\t\tstd::ofstream out(filename);\n\t\t\tout << \"graph spectralgraph {\\n\";\n\t\t\tout << \"overlap = scale;\\n\";\n\n\t\t\tauto cluster = spectralClusters(false);\n\n\t\t\tstd::unordered_map nodeCulster;\n\n\t\t\tfor (size_t i = 0; i < cluster.clusters.size(); i++)\n\t\t\t{\n\t\t\t\tnodeCulster[cluster.clusters[i].id] = cluster.clusters[i].cluster_id;\n\n\t\t\t\tif (cluster.clusters[i].cluster_id == 0)\n\t\t\t\t\tout << cluster.clusters[i].id << \"[color = blue];\" << std::endl;\n\t\t\t\telse if (cluster.clusters[i].cluster_id == 1)\n\t\t\t\t\tout << cluster.clusters[i].id << \"[color = green];\" << std::endl;\n\t\t\t\telse \n\t\t\t\t\tout << cluster.clusters[i].id << \"[color = red];\" << std::endl;\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < n_vertex; i++)\n\t\t\t{\n\t\t\t\tfor (int j = 0; j < i; j++)\n\t\t\t\t{\n\t\t\t\t\tif (is_connected(i, j))\n\t\t\t\t\t{\n\t\t\t\t\t\tout << i << \"--\" << j << \";\" << std::endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tout << \"}\\n\";\n\n\t\t\tout.close();\n\t\t}\n\n\t\tClusterCollection spectralClusters(bool normalize = false)\n\t\t{\n\t\t\tClusterCollection cc;\n\n\t\t\tcc.size = 2;\n\n\t\t\tEigen::VectorXf fv = getFiedlerVector(normalize);\n\n\t\t\tstd::cout << fv << std::endl;\n\n\t\t\tfor (int i = 0; i < fv.size(); i++)\n\t\t\t{\n\t\t\t\tClusteredNode cnode;\n\t\t\t\tcnode.id = i;\n\n\t\t\t\tif (fabs(fv(i)) < 0.001) {\n\t\t\t\t\tcnode.cluster_id = 0;\n\t\t\t\t} else if (fv(i) > 0.0) {\t\t\n\t\t\t\t\tcnode.cluster_id = 1;\n\t\t\t\t} else {\n\t\t\t\t\tcnode.cluster_id = 2;\n\t\t\t\t}\n\n\t\t\t\tcc.clusters.push_back(cnode);\n\t\t\t}\n\n\t\t\treturn cc;\n\t\t}\n\n\t\t/*static bool isospectralLaplacian(SpectralGraph g1, SpectralGraph g2, double epsilon) {\n\n\t\t\tEigen::VectorXf normalizedEg1 = g1.laplacianSpectrum().normalized();\n\t\t\tEigen::VectorXf normalizedEg2 = g2.laplacianSpectrum().normalized();\t\n\n\t\t\tif (normalizedEg1.cols() != normalizedEg2.cols()) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (normalizedEg1.rows() != normalizedEg2.rows()) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < normalizedEg1.rows(); i++)\t{\n\t\t\t\tfor (int j = 0; j < normalizedEg1.cols(); j++)\t{\n\t\t\t\t\tif (abs(normalizedEg1(i, j) - normalizedEg2(i, j)) > epsilon) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\tstatic double distance(SpectralGraph g1, SpectralGraph g2) {\n\t\t\tEigen::VectorXf normalizedEg1 = g1.laplacianSpectrum().normalized();\n\t\t\tEigen::VectorXf normalizedEg2 = g2.laplacianSpectrum().normalized();\t\n\n\t\t\tdouble dist = 0.0;\n\n\t\t\tif (normalizedEg1.cols() != normalizedEg2.cols()) {\n\t\t\t\treturn 0.0;\n\t\t\t}\n\n\t\t\tif (normalizedEg1.rows() != normalizedEg2.rows()) {\n\t\t\t\treturn 0.0;\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < normalizedEg1.rows(); i++)\t{\n\t\t\t\tfor (int j = 0; j < normalizedEg1.cols(); j++)\t{\n\t\t\t\t\tdist += abs(normalizedEg1(i, j) - normalizedEg2(i, j));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn dist;\n\t\t}*/\n\t};\n}\n\n#endif", "meta": {"hexsha": "49d761b56936a5492ef83b0ac74132db2de34cc2", "size": 9389, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/SpectralGraph.hpp", "max_stars_repo_name": "GHamrouni/R7", "max_stars_repo_head_hexsha": "338ab32e7fc952c5ba87cf17e9b69c8dd18064e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-07-21T19:10:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-07T00:02:57.000Z", "max_issues_repo_path": "src/SpectralGraph.hpp", "max_issues_repo_name": "GHamrouni/R7", "max_issues_repo_head_hexsha": "338ab32e7fc952c5ba87cf17e9b69c8dd18064e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SpectralGraph.hpp", "max_forks_repo_name": "GHamrouni/R7", "max_forks_repo_head_hexsha": "338ab32e7fc952c5ba87cf17e9b69c8dd18064e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.95599022, "max_line_length": 107, "alphanum_fraction": 0.6090105443, "num_tokens": 3096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452771, "lm_q2_score": 0.822189121808099, "lm_q1q2_score": 0.7859974687963389}} {"text": "#include \n#include \n\nint main(int argc, char **argv)\n{\n using namespace boost::numeric::ublas;\n using std::cout;\n using std::endl;\n\n int xlen = 5; //(int) *argv[0];\n int ylen = 5; //(int) *argv[1];\n long double xmin = -10; //(long double) *argv[2];\n long double xmax = 10; //(long double) *argv[3];\n long double ymin = -10; //(long double) *argv[4];\n long double ymax = 10; //(long double) *argv[5];\n long double dx = (xmax - xmin)/(xlen-1);\n long double dy = (ymax - ymin)/(ylen-1);\n\n matrix > cplane(ylen,xlen);\n\n for (unsigned r = 0; r < cplane.size1(); r++)\n {\n for (unsigned c = 0; c < cplane.size2(); c++)\n {\n cplane(r,c) = std::complex(xmin + c*dx, ymin + r*dy);\n }\n }\n for (unsigned r = 0; r < cplane.size1(); r++)\n {\n for (unsigned c = 0; c < cplane.size2(); c++)\n {\n cout << xmin + c*dx << \" + \" << ymin + r*dy << \"i\" << \" \";\n }\n cout << endl;\n }\n\n}", "meta": {"hexsha": "fad5363dc0752626e75c3d0f04b147c3fc38446c", "size": 1111, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/prettyprint/prettyprint.cc", "max_stars_repo_name": "chapman-cs510-2017f/cw-13-evan_logan", "max_stars_repo_head_hexsha": "9ab5e9923c1cf6ea8ff5d1d371a8d7474616ea6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/prettyprint/prettyprint.cc", "max_issues_repo_name": "chapman-cs510-2017f/cw-13-evan_logan", "max_issues_repo_head_hexsha": "9ab5e9923c1cf6ea8ff5d1d371a8d7474616ea6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/prettyprint/prettyprint.cc", "max_forks_repo_name": "chapman-cs510-2017f/cw-13-evan_logan", "max_forks_repo_head_hexsha": "9ab5e9923c1cf6ea8ff5d1d371a8d7474616ea6d", "max_forks_repo_licenses": ["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.027027027, "max_line_length": 78, "alphanum_fraction": 0.502250225, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750373915658, "lm_q2_score": 0.8244619328462579, "lm_q1q2_score": 0.7859389798619392}} {"text": "// laplace_example.cpp\n\n// Copyright Paul A. Bristow 2008, 2010.\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Example of using laplace (& comparing with normal) distribution.\n\n// Note that this file contains Quickbook mark-up as well as code\n// and comments, don't change any of the special comment mark-ups!\n\n//[laplace_example1\n/*`\nFirst we need some includes to access the laplace & normal distributions\n(and some std output of course).\n*/\n\n#include // for laplace_distribution\n using boost::math::laplace; // typedef provides default type is double.\n#include // for normal_distribution\n using boost::math::normal; // typedef provides default type is double.\n\n#include \n using std::cout; using std::endl; using std::left; using std::showpoint; using std::noshowpoint;\n#include \n using std::setw; using std::setprecision;\n#include \n using std::numeric_limits;\n\nint main()\n{\n cout << \"Example: Laplace distribution.\" << endl;\n\n try\n {\n { // Traditional tables and values.\n/*`Let's start by printing some traditional tables.\n*/ \n double step = 1.; // in z \n double range = 4; // min and max z = -range to +range.\n //int precision = 17; // traditional tables are only computed to much lower precision.\n int precision = 4; // traditional table at much lower precision.\n int width = 10; // for use with setw.\n\n // Construct standard laplace & normal distributions l & s\n normal s; // (default location or mean = zero, and scale or standard deviation = unity)\n cout << \"Standard normal distribution, mean or location = \"<< s.location()\n << \", standard deviation or scale = \" << s.scale() << endl;\n laplace l; // (default mean = zero, and standard deviation = unity)\n cout << \"Laplace normal distribution, location = \"<< l.location()\n << \", scale = \" << l.scale() << endl;\n\n/*` First the probability distribution function (pdf).\n*/\n cout << \"Probability distribution function values\" << endl;\n cout << \" z PDF normal laplace (difference)\" << endl;\n cout.precision(5);\n for (double z = -range; z < range + step; z += step)\n {\n cout << left << setprecision(3) << setw(6) << z << \" \" \n << setprecision(precision) << setw(width) << pdf(s, z) << \" \"\n << setprecision(precision) << setw(width) << pdf(l, z)<< \" (\"\n << setprecision(precision) << setw(width) << pdf(l, z) - pdf(s, z) // difference.\n << \")\" << endl;\n }\n cout.precision(6); // default\n/*`Notice how the laplace is less at z = 1 , but has 'fatter' tails at 2 and 3. \n\n And the area under the normal curve from -[infin] up to z,\n the cumulative distribution function (cdf).\n*/\n // For a standard distribution \n cout << \"Standard location = \"<< s.location()\n << \", scale = \" << s.scale() << endl;\n cout << \"Integral (area under the curve) from - infinity up to z \" << endl;\n cout << \" z CDF normal laplace (difference)\" << endl;\n for (double z = -range; z < range + step; z += step)\n {\n cout << left << setprecision(3) << setw(6) << z << \" \" \n << setprecision(precision) << setw(width) << cdf(s, z) << \" \"\n << setprecision(precision) << setw(width) << cdf(l, z) << \" (\"\n << setprecision(precision) << setw(width) << cdf(l, z) - cdf(s, z) // difference.\n << \")\" << endl;\n }\n cout.precision(6); // default\n\n/*`\nPretty-printing a traditional 2-dimensional table is left as an exercise for the student,\nbut why bother now that the Boost Math Toolkit lets you write\n*/\n double z = 2.; \n cout << \"Area for gaussian z = \" << z << \" is \" << cdf(s, z) << endl; // to get the area for z.\n cout << \"Area for laplace z = \" << z << \" is \" << cdf(l, z) << endl; // \n/*`\nCorrespondingly, we can obtain the traditional 'critical' values for significance levels.\nFor the 95% confidence level, the significance level usually called alpha,\nis 0.05 = 1 - 0.95 (for a one-sided test), so we can write\n*/\n cout << \"95% of gaussian area has a z below \" << quantile(s, 0.95) << endl;\n cout << \"95% of laplace area has a z below \" << quantile(l, 0.95) << endl;\n // 95% of area has a z below 1.64485\n // 95% of laplace area has a z below 2.30259\n/*`and a two-sided test (a comparison between two levels, rather than a one-sided test)\n\n*/\n cout << \"95% of gaussian area has a z between \" << quantile(s, 0.975)\n << \" and \" << -quantile(s, 0.975) << endl;\n cout << \"95% of laplace area has a z between \" << quantile(l, 0.975)\n << \" and \" << -quantile(l, 0.975) << endl;\n // 95% of area has a z between 1.95996 and -1.95996\n // 95% of laplace area has a z between 2.99573 and -2.99573\n/*`Notice how much wider z has to be to enclose 95% of the area.\n*/\n }\n//] [/[laplace_example1]\n }\n catch(const std::exception& e)\n { // Always useful to include try & catch blocks because default policies \n // are to throw exceptions on arguments that cause errors like underflow, overflow. \n // Lacking try & catch blocks, the program will abort without a message below,\n // which may give some helpful clues as to the cause of the exception.\n std::cout <<\n \"\\n\"\"Message from thrown exception was:\\n \" << e.what() << std::endl;\n }\n return 0;\n} // int main()\n\n/*\n\nOutput is:\n\nExample: Laplace distribution.\nStandard normal distribution, mean or location = 0, standard deviation or scale = 1\nLaplace normal distribution, location = 0, scale = 1\nProbability distribution function values\n z PDF normal laplace (difference)\n-4 0.0001338 0.009158 (0.009024 )\n-3 0.004432 0.02489 (0.02046 )\n-2 0.05399 0.06767 (0.01368 )\n-1 0.242 0.1839 (-0.05803 )\n0 0.3989 0.5 (0.1011 )\n1 0.242 0.1839 (-0.05803 )\n2 0.05399 0.06767 (0.01368 )\n3 0.004432 0.02489 (0.02046 )\n4 0.0001338 0.009158 (0.009024 )\nStandard location = 0, scale = 1\nIntegral (area under the curve) from - infinity up to z \n z CDF normal laplace (difference)\n-4 3.167e-005 0.009158 (0.009126 )\n-3 0.00135 0.02489 (0.02354 )\n-2 0.02275 0.06767 (0.04492 )\n-1 0.1587 0.1839 (0.02528 )\n0 0.5 0.5 (0 )\n1 0.8413 0.8161 (-0.02528 )\n2 0.9772 0.9323 (-0.04492 )\n3 0.9987 0.9751 (-0.02354 )\n4 1 0.9908 (-0.009126 )\nArea for gaussian z = 2 is 0.97725\nArea for laplace z = 2 is 0.932332\n95% of gaussian area has a z below 1.64485\n95% of laplace area has a z below 2.30259\n95% of gaussian area has a z between 1.95996 and -1.95996\n95% of laplace area has a z between 2.99573 and -2.99573\n\n*/\n\n", "meta": {"hexsha": "ed99dba21208dfd475c92ee407148840cb66ab01", "size": 7049, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/math/example/laplace_example.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/math/example/laplace_example.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/math/example/laplace_example.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 41.4647058824, "max_line_length": 99, "alphanum_fraction": 0.6059015463, "num_tokens": 2086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8723473813156294, "lm_q1q2_score": 0.7855747960590835}} {"text": "#include \n#include \n#include \n#include \n\n//! \\brief Compute y = A*x for A banded matrix with diagonal structure\n//! \\param[in] a n-1 dim. vector for upper diagonal\n//! \\param[in] b n-2 dim. vector for second lower diagonal\n//! \\param[in] x n dim. vector for Ax = y\n//! \\param[out] y n dim. vector y = Ax\ntemplate \nvoid multAx(const Vector & a, const Vector & b, const Vector & x, Vector & y) {\n unsigned int n = x.size();\n if( a.size() < n - 1 || b.size() < n - 2 ) {\n // Size check, error if do not match\n std::cerr << \"Error: size mismatch!\" << std::endl;\n return;\n }\n y.resize(n); // Ensure y has size n\n \n // Handle first two rows\n if(n > 1) y(0) = 2*x(0) + a(0)*x(1);\n else { // Special case n = 1\n y(0) = 2*x(0);\n return;\n }\n if(n > 2) y(1) = 2*x(1) + a(1)*x(2);\n else { // Special case n = 2\n y(1) = 2*x(1);\n return;\n }\n \n // Row if n > 3 and without last row\n for(unsigned int i = 2; i < n-1; ++i) {\n y(i) = 2*x(i) + b(i-2)*x(i-2) + a(i)*x(i+1);\n }\n \n // Last row special case\n if(n > 2) y(n-1) = 2*x(n-1) + b(n-3)*x(n-3);\n}\n\n//! \\brief Solve y = A*x for A banded matrix with upper tirangular sparse structure\n//! \\param[in] a n-1 dim. vector for upper diagonal\n//! \\param[in] r n dim. vector for Ax = r\n//! \\param[out] x n dim. solution vector r = Ax\ntemplate \nvoid solvelseAupper(const Vector & a, const Vector & r, Vector & x) {\n // Dimensions + ensure correct dimensions\n unsigned int n = r.size();\n x.resize(n);\n \n // Backward substitution\n x(n-1) = 0.5 * r(n-1);\n for(int j = n-2; j >= 0; --j) {\n x(j) = 0.5*(r(j) - a(j)*x(j+1));\n }\n}\n\n//! \\brief Solve y = A*x for A banded matrix using Gaussian-elimination (no pivot)\n//! \\param[in] a n-1 dim. vector for upper diagonal\n//! \\param[in] b n-2 dim. vector for second lower diagonal\n//! \\param[in] r n dim. vector for Ax = r\n//! \\param[out] x n dim. solution vector r = Ax\ntemplate \nvoid solvelseA(const Vector & a, const Vector & b, const Vector & r, Vector & x) {\n // Setup type, size and copy data\n typedef typename Vector::Scalar Scalar;\n int n = r.size();\n x = r;\n \n // Fill in matrix, we reserve 5 nnz per row for Gauss fill-in\n Eigen::SparseMatrix A(n,n);\n A.reserve(5);\n for(int i = 0; i < n; ++i) {\n A.insert(i,i) = 2;\n if(i < n-1) A.insert(i,i+1) = a(i);\n if(i >= 2) A.insert(i,i-2) = b(i-2);\n }\n A.makeCompressed();\n \n // 1st stage: elimination (in place)\n for(int i = 0; i < n-1; ++i) {\n for(int k = i+1; k < std::min(i+3,n); ++k) {\n Scalar fac = A.coeffRef(k,i)/A.coeffRef(i,i);\n for(int l = i; l < std::min(i+3,n); ++l) {\n A.coeffRef(k,l) -= fac * A.coeffRef(i,l);\n }\n x(k) -= fac * x(i);\n }\n }\n \n // 2nd stage: backwards substitution (in place)\n x(n-1) /= A.coeffRef(n-1,n-1);\n for(int i = n-2; i >= 0; --i) {\n for(int k = i+1; k < std::min(i+3,n); ++k) {\n x(i) -= x(k)*A.coeffRef(i,k);\n }\n x(i) /= A.coeffRef(i,i);\n }\n}\n\n//! \\brief Solve y = A*x for A banded matrix using SparseLU\n//! \\param[in] a n-1 dim. vector for upper diagonal\n//! \\param[in] b n-2 dim. vector for second lower diagonal\n//! \\param[in] r n dim. vector for Ax = r\n//! \\param[out] x n dim. solution vector r = Ax\ntemplate \nvoid solvelseAEigen(const Vector & a, const Vector & b, const Vector & r, Vector & x) {\n // Dimensions\n typedef typename Vector::Scalar Scalar;\n unsigned int n = r.size();\n \n // Fill in matrix + reserve\n Eigen::SparseMatrix A(n,n);\n A.reserve(3);\n for(unsigned int i = 0; i < n; ++i) {\n A.insert(i,i) = 2;\n if(i < n-1) A.insert(i,i+1) = a(i);\n if(i >= 2) A.insert(i,i-2) = b(i-2);\n }\n A.makeCompressed();\n \n // Call SparseLU\n Eigen::SparseLU< Eigen::SparseMatrix > solver;\n solver.analyzePattern(A); \n solver.compute(A);\n x = solver.solve(r);\n}\n\nint main() {\n // Random vectors to check correctness\n std::cout << \"*** Check correctness of banded solvers implementations\" << std::endl;\n int n = 9;\n Eigen::VectorXd a = Eigen::VectorXd::Random(n-1);\n Eigen::VectorXd b = Eigen::VectorXd::Zero(n-2);\n Eigen::VectorXd y = Eigen::VectorXd::Random(n);\n Eigen::VectorXd x;\n \n std::cout << \"Original:\" << y << std::endl;\n \n // Compute y = A*inv(A)*y\n solvelseAupper(a,y,x);\n multAx(a,b,x,y);\n \n b = Eigen::VectorXd::Random(n-2);\n \n // Should be same as before\n std::cout << \"Upper:\" << y << std::endl;\n \n // Compute y = A*inv(A)*y\n solvelseA(a,b,y,x);\n multAx(a,b,x,y);\n \n // Should be same as before\n std::cout << \"Own:\" << y << std::endl;\n \n // Compute y = A*inv(A)*y\n solvelseAEigen(a,b,y,x);\n multAx(a,b,x,y);\n \n // Should be same as before\n std::cout << \"Eigen:\" << y << std::endl;\n \n}\n", "meta": {"hexsha": "d2ba4587062bbefadc6b017999da9c725ced017f", "size": 5088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/solutions/solution_2/banded_matrix.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/solutions/solution_2/banded_matrix.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/solutions/solution_2/banded_matrix.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8363636364, "max_line_length": 89, "alphanum_fraction": 0.5389150943, "num_tokens": 1649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.872347369700144, "lm_q1q2_score": 0.7855747902565772}} {"text": "#pragma once\n\n#include \n\n#include \n\nnamespace math \n{\n\nconstexpr double DEFAULT_STEP_SIZE = 0.0009765625;\n\ntemplate\nusing Matrix = Eigen::Matrix;\n\ntemplate\nusing Vector = Eigen::Matrix;\n\ntemplate\nbool is_equal(const Matrix<_rows, _cols> &mat1, const Matrix<_rows, _cols> &mat2, const double tol = 1e-8)\n{\n return ((mat1 - mat2).array().abs() < tol).all();\n}\n\ntemplate\nbool is_symmetric(const Matrix<_rows, _rows> &mat, const double tol = 1e-8)\n{\n return math::is_equal<_rows,_rows>(mat, mat.transpose(), tol);\n}\n\ntemplate\nVector<_rows> gradient(\n const Callable &func, \n const Vector<_rows> &pt, const double delta = DEFAULT_STEP_SIZE)\n{\n IS_GREATER(delta, 0);\n\n const int dim = pt.size();\n IS_GREATER(dim, 0);\n\n Vector<_rows> gradient(dim);\n\n for (int i = 0; i < dim; ++i)\n {\n Vector<_rows> pt_positive = pt;\n pt_positive[i] += delta;\n\n Vector<_rows> pt_negative = pt;\n pt_negative[i] -= delta;\n\n gradient(i) = (func(pt_positive) - func(pt_negative)) / (2.0 * delta);\n }\n\n return gradient;\n}\n\ntemplate\nMatrix<_out_rows, _in_rows> jacobian(\n const Callable &func, \n const Vector<_in_rows> &pt, const double delta = DEFAULT_STEP_SIZE)\n{\n IS_GREATER(delta, 0);\n\n Matrix<_out_rows, _in_rows> jacobian; jacobian.setZero();\n\n for (int i = 0; i < _in_rows; ++i)\n {\n Vector<_in_rows> pt_positive = pt;\n pt_positive[i] += delta;\n\n Vector<_in_rows> pt_negative = pt;\n pt_negative[i] -= delta;\n\n jacobian.col(i) = (func(pt_positive) - func(pt_negative)) / (2.0 * delta);\n }\n\n return jacobian;\n}\n\ntemplate\nMatrix<_rows, _rows> hessian(\n const Callable &func, \n const Vector<_rows> &pt, const double delta = DEFAULT_STEP_SIZE)\n{\n IS_GREATER(delta, 0);\n\n // Precompute constants.\n const double two_delta = 2.0*delta;\n const double delta_sq = delta*delta;\n const double ij_eq_div = 12.*delta_sq;\n const double ij_neq_div = 4.*delta_sq;\n \n Matrix<_rows, _rows> hessian; hessian.setZero();\n // Central difference approximation based on \n // https://v8doc.sas.com/sashtml/ormp/chap5/sect28.htm\n for (int i = 0; i < _rows; ++i)\n {\n for (int j = i; j < _rows; ++j)\n {\n Vector<_rows> p1 = pt;\n Vector<_rows> p2 = pt;\n Vector<_rows> p3 = pt;\n Vector<_rows> p4 = pt;\n double value = 0;\n if (i == j)\n {\n p1[i] += two_delta; \n p2[i] += delta;\n p3[i] -= delta;\n p4[i] -= two_delta;\n value = (-func(p1) + 16.*(func(p2) + func(p3)) - 30.*func(pt) - func(p4)) \n / (ij_eq_div);\n } \n else\n {\n p1[i] += delta;\n p1[j] += delta;\n\n p2[i] += delta;\n p2[j] -= delta;\n\n p3[i] -= delta;\n p3[j] += delta;\n\n p4[i] -= delta;\n p4[j] -= delta;\n\n value = (func(p1) - func(p2) - func(p3) + func(p4)) / (ij_neq_div);\n }\n\n hessian(i,j) = value;\n hessian(j,i) = value;\n }\n }\n\n return hessian;\n}\n\ntemplate\nMatrix<_rows, _rows> project_to_psd(const Matrix<_rows, _rows> &symmetric_mat, const double min_eigval)\n{\n // Cheap check to confirm matrix is square.\n IS_EQUAL(symmetric_mat.rows(), symmetric_mat.cols());\n\n // O(n^2) check to make sure that the matrix is symmetric.\n IS_TRUE(math::is_symmetric(symmetric_mat));\n\n const Eigen::SelfAdjointEigenSolver> es(symmetric_mat);\n Matrix<_rows, _rows> evals = es.eigenvalues().asDiagonal();\n const Matrix<_rows, _rows> evecs = es.eigenvectors();\n\n // Indices of eigen values that are less than the minimum eigenvalue threshold.\n int num_failed_evals = 0;\n const int num_evals = evals.rows();\n for (int i = 0; i < num_evals; ++i)\n {\n if (evals(i,i) < min_eigval)\n {\n ++num_failed_evals;\n evals(i,i) = min_eigval;\n }\n }\n // If we didn't have eigenvalues less than the minimum threshold, then return the original\n // matrix.\n if (num_failed_evals == 0)\n {\n return symmetric_mat;\n }\n\n // We can reconstruct with P D P\\inv = P D P^T if P is orthonormal.\n const Matrix<_rows, _rows> projection = evecs * evals * evecs.transpose() ;\n return projection;\n}\n\ntemplate\nvoid check_psd(const Matrix<_rows, _rows> &mat, const double min_eigval)\n{\n // Cheap check to confirm matrix is square.\n IS_EQUAL(mat.rows(), mat.cols());\n\n // O(n^2) check to make sure that the matrix is symmetric.\n IS_TRUE(math::is_symmetric(mat));\n\n const Eigen::SelfAdjointEigenSolver> es(mat, Eigen::EigenvaluesOnly);\n const auto evals = es.eigenvalues();\n\n for (int i = 0; i < evals.size(); ++i)\n {\n // Throw an exception if this is not true.\n IS_GREATER_EQUAL(evals(i), min_eigval);\n }\n}\n\n} // namespace math \n", "meta": {"hexsha": "bc6e095200f2f7cf64f7149b325c7a01f0aa2144", "size": 5340, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/utils/math_utils_temp.hh", "max_stars_repo_name": "LAIRLAB/qr_trees", "max_stars_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T08:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T08:42:33.000Z", "max_issues_repo_path": "src/utils/math_utils_temp.hh", "max_issues_repo_name": "LAIRLAB/qr_trees", "max_issues_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/math_utils_temp.hh", "max_forks_repo_name": "LAIRLAB/qr_trees", "max_forks_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-07-10T03:25:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T15:58:44.000Z", "avg_line_length": 27.5257731959, "max_line_length": 106, "alphanum_fraction": 0.5874531835, "num_tokens": 1481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159727, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.7854545916684331}} {"text": "#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace Eigen;\n\n#define MATRIX_SIZE 100\n\nint main(int argc, char** argv) {\n MatrixXd matrix_NN = MatrixXd::Random(MATRIX_SIZE, MATRIX_SIZE);\n matrix_NN = matrix_NN * matrix_NN.transpose(); // 保证实对称矩阵\n SelfAdjointEigenSolver eigen_solver(matrix_NN); // 实对称矩阵可以保证正定成功\n cout << \"Eigen values = \\n\" << eigen_solver.eigenvalues() << endl;\n cout << \"Eigen vectors = \\n\" << eigen_solver.eigenvectors() << endl;\n MatrixXd v_Nd = MatrixXd::Random(MATRIX_SIZE, 1);\n\n clock_t time_stt = clock();\n Matrix x;\n\n // QR\n x = matrix_NN.colPivHouseholderQr().solve(v_Nd);\n cout << \"time of Qr decomposition is \"\n << 1000 * (clock() - time_stt) / (double) CLOCKS_PER_SEC << \"ms\" << endl;\n cout << \"x = \" << x.transpose() << endl;\n \n // Cholesky\n time_stt = clock();\n x = matrix_NN.ldlt().solve(v_Nd);\n cout << \"time of ldlt decomposition is \"\n << 1000 * (clock() - time_stt) / (double) CLOCKS_PER_SEC << \"ms\" << endl;\n cout << \"x = \" << x.transpose() << endl;\n \n return 0;\n}", "meta": {"hexsha": "e9ef77b49d09fff89acbc8e8ea76bb83a10817ee", "size": 1133, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "assignment-02/ex1.cpp", "max_stars_repo_name": "daigz1224/course-slam-assignments", "max_stars_repo_head_hexsha": "0b7c646472d346e4cbff770214716ef03136adce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assignment-02/ex1.cpp", "max_issues_repo_name": "daigz1224/course-slam-assignments", "max_issues_repo_head_hexsha": "0b7c646472d346e4cbff770214716ef03136adce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment-02/ex1.cpp", "max_forks_repo_name": "daigz1224/course-slam-assignments", "max_forks_repo_head_hexsha": "0b7c646472d346e4cbff770214716ef03136adce", "max_forks_repo_licenses": ["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.4722222222, "max_line_length": 80, "alphanum_fraction": 0.6531332745, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538936, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7854257907366414}} {"text": "#include \r\n#include \r\n\r\nusing namespace Eigen;\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n MatrixXf m(2,2);\r\n m << 1,-2,\r\n -3,4;\r\n\r\n cout << \"1-norm(m) = \" << m.cwiseAbs().colwise().sum().maxCoeff()\r\n << \" == \" << m.colwise().lpNorm<1>().maxCoeff() << endl;\r\n\r\n cout << \"infty-norm(m) = \" << m.cwiseAbs().rowwise().sum().maxCoeff()\r\n << \" == \" << m.rowwise().lpNorm<1>().maxCoeff() << endl;\r\n}\r\n", "meta": {"hexsha": "3b4589ac3ccb8c101bb22d6b6187c292f0cf957b", "size": 465, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/Tutorial_ReductionsVisitorsBroadcasting_reductions_operatornorm.cpp", "max_stars_repo_name": "k4rth33k/dnnc-operators", "max_stars_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T14:35:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-11T23:59:22.000Z", "max_issues_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/Tutorial_ReductionsVisitorsBroadcasting_reductions_operatornorm.cpp", "max_issues_repo_name": "k4rth33k/dnnc-operators", "max_issues_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-08-12T04:38:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T16:32:13.000Z", "max_forks_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/Tutorial_ReductionsVisitorsBroadcasting_reductions_operatornorm.cpp", "max_forks_repo_name": "k4rth33k/dnnc-operators", "max_forks_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-08-15T13:29:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-09T17:08:04.000Z", "avg_line_length": 24.4736842105, "max_line_length": 76, "alphanum_fraction": 0.4795698925, "num_tokens": 143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.8705972751232808, "lm_q1q2_score": 0.7852096925446083}} {"text": "#include \n#include \n\n//Transform, Translation, Scaling, Rotation2D and 3D rotations (Quaternion, AngleAxis)\n\n#if KDL_FOUND==1\n#include \n#endif\n\n//The value of KDL_FOUND has been set via target_compile_definitions in CMake\n\n\nEigen::Matrix3d eulerAnglesToRotationMatrix(double roll, double pitch,double yaw)\n{\n Eigen::AngleAxisd rollAngle(roll, Eigen::Vector3d::UnitX());\n Eigen::AngleAxisd pitchAngle(pitch, Eigen::Vector3d::UnitY());\n Eigen::AngleAxisd yawAngle(yaw, Eigen::Vector3d::UnitZ());\n Eigen::Quaternion q = yawAngle * pitchAngle * rollAngle;\n Eigen::Matrix3d rotationMatrix = q.matrix();\n return rotationMatrix;\n}\n\nvoid transformation()\n{\n/*\nGreat Tutorial:\nhttp://planning.cs.uiuc.edu/node102.html\nhttp://euclideanspace.com/maths/geometry/rotations/conversions/index.htm\n\nTait–Bryan angles: Z1Y2X3 in the wiki page:\nhttps://en.wikipedia.org/wiki/Euler_angles\n yaw:\n A yaw is a counterclockwise rotation of alpha about the z-axis. The\n rotation matrix is given by\n\n R_z\n\n |cos(alpha) -sin(alpha) 0|\n |sin(apha) cos(alpha) 0|\n | 0 0 1|\n\n pitch:\n R_y\n A pitch is a counterclockwise rotation of beta about the y-axis. The\n rotation matrix is given by\n\n |cos(beta) 0 sin(beta)|\n |0 1 0 |\n |-sin(beta) 0 cos(beta)|\n\n roll:\n A roll is a counterclockwise rotation of gamma about the x-axis. The\n rotation matrix is given by\n R_x\n |1 0 0|\n |0 cos(gamma) -sin(gamma)|\n |0 sin(gamma) cos(gamma)|\n\n\n\n It is important to note that R_z R_y R_x performs the roll first, then the pitch, and finally the yaw\n Roration matrix: R_z*R_y*R_x\n\n*/\n/////////////////////////////////////Rotation Matrix (Tait–Bryan)///////////////////////////////\n double roll, pitch, yaw;\n roll=M_PI/2;\n pitch=M_PI/2;\n yaw=0;//M_PI/6;\n std::cout << \"Roll : \" << roll << std::endl;\n std::cout << \"Pitch : \" << pitch << std::endl;\n std::cout << \"Yaw : \" << yaw << std::endl;\n\n/////////////////////////////////////Rotation Matrix (Tait–Bryan)///////////////////////////////\n\n // Roll, Pitch, Yaw to Rotation Matrix\n //Eigen::AngleAxis rollAngle(roll, Eigen::Vector3d(1,0,0));\n\n std::cout << \"Roll : \" << roll << std::endl;\n std::cout << \"Pitch : \" << pitch << std::endl;\n std::cout << \"Yaw : \" << yaw << std::endl;\n\n\n\n // Roll, Pitch, Yaw to Rotation Matrix\n //Eigen::AngleAxis rollAngle(roll, Eigen::Vector3d(1,0,0));\n Eigen::AngleAxisd rollAngle(roll, Eigen::Vector3d::UnitX());\n Eigen::AngleAxisd pitchAngle(pitch, Eigen::Vector3d::UnitY());\n Eigen::AngleAxisd yawAngle(yaw, Eigen::Vector3d::UnitZ());\n\n\n\n//////////////////////////////////////// Quaternion ///////////////////////////////////////////\n Eigen::Quaternion q = yawAngle * pitchAngle * rollAngle;\n\n \n //Quaternion to Rotation Matrix\n Eigen::Matrix3d rotationMatrix = q.matrix();\n std::cout << \"3x3 Rotation Matrix\" << std::endl;\n\n std::cout << rotationMatrix << std::endl;\n\n Eigen::Quaterniond quaternion_mat(rotationMatrix);\n std::cout << \"Quaternion X: \" << quaternion_mat.x() << std::endl;\n std::cout << \"Quaternion Y: \" << quaternion_mat.y() << std::endl;\n std::cout << \"Quaternion Z: \" << quaternion_mat.z() << std::endl;\n std::cout << \"Quaternion W: \" << quaternion_mat.w() << std::endl;\n\n\n\n//////////////////////////////////////// Rodrigues ///////////////////////////////////////////\n\n\n //Rotation Matrix to Rodrigues\n Eigen::AngleAxisd rodrigues(rotationMatrix );\n std::cout<<\"Rodrigues Angle:\\n\"< q = yawAngle * pitchAngle * rollAngle;\n Eigen::Matrix3d rotationMatrix = q.matrix();\n\n std::cout << \"Rotation Matrix is:\" << std::endl;\n std::cout << rotationMatrix << std::endl;\n\n std::cout << \"roll is Pi/\"\n << M_PI / atan2(rotationMatrix(2, 1), rotationMatrix(2, 2))\n << std::endl;\n std::cout << \"pitch: Pi/\"\n << M_PI / atan2(-rotationMatrix(2, 0),\n std::pow(\n rotationMatrix(2, 1) * rotationMatrix(2, 1) + rotationMatrix(2, 2) * rotationMatrix(2, 2),\n 0.5))\n << std::endl;\n std::cout << \"yaw is Pi/\"\n << M_PI / atan2(rotationMatrix(1, 0), rotationMatrix(0, 0))\n << std::endl;\n}\n\nvoid transformExample()\n{\n/*\nThe class Eigen::Transform represents either\n1) an affine, or\n2) a projective transformation\nusing homogenous calculus.\n\nFor instance, an affine transformation A is composed of a linear part L and a translation t such that transforming a point p by A is equivalent to:\n\np' = L * p + t\n\nUsing homogeneous vectors:\n\n [p'] = [L t] * [p] = A * [p]\n [1 ] [0 1] [1] [1]\n\nRef: https://stackoverflow.com/questions/35416880/what-does-transformlinear-return-in-the-eigen-library\n\nDifference Between Projective and Affine Transformations\n1) The projective transformation does not preserve parallelism, length, and angle. But it still preserves collinearity and incidence.\n2) Since the affine transformation is a special case of the projective transformation,\nit has the same properties. However unlike projective transformation, it preserves parallelism.\n\nRef: https://www.graphicsmill.com/docs/gm5/Transformations.htm\n*/\n\n float arrVertices [] = { -1.0 , -1.0 , -1.0 ,\n 1.0 , -1.0 , -1.0 ,\n 1.0 , 1.0 , -1.0 ,\n -1.0 , 1.0 , -1.0 ,\n -1.0 , -1.0 , 1.0 ,\n 1.0 , -1.0 , 1.0 ,\n 1.0 , 1.0 , 1.0 ,\n -1.0 , 1.0 , 1.0};\n Eigen::MatrixXf mVertices = Eigen::Map < Eigen::Matrix > ( arrVertices ) ;\n Eigen::Transform t = Eigen::Transform ::Identity();\n t.scale ( 0.8f ) ;\n t.rotate ( Eigen::AngleAxisf (0.25f * M_PI , Eigen::Vector3f::UnitX () ) ) ;\n t.translate ( Eigen::Vector3f (1.5 , 10.2 , -5.1) ) ;\n std::cout << t * mVertices.colwise().homogeneous () << std::endl;\n}\n\n\nEigen::Matrix4f createAffinematrix(float a, float b, float c, Eigen::Vector3f trans)\n{\n {\n Eigen::Transform t;\n t = Eigen::Translation(trans);\n t.rotate(Eigen::AngleAxis(a, Eigen::Vector3f::UnitX()));\n t.rotate(Eigen::AngleAxis(b, Eigen::Vector3f::UnitY()));\n t.rotate(Eigen::AngleAxis(c, Eigen::Vector3f::UnitZ()));\n return t.matrix();\n }\n\n\n {\n /*\n The difference between the first implementation and the second is like the difference between \"Fix Angle\" and \"Euler Angle\", you can\n https://www.youtube.com/watch?v=09xVHo1JudY\n */\n Eigen::Transform t;\n t = Eigen::AngleAxis(c, Eigen::Vector3f::UnitZ());\n t.prerotate(Eigen::AngleAxis(b, Eigen::Vector3f::UnitY()));\n t.prerotate(Eigen::AngleAxis(a, Eigen::Vector3f::UnitX()));\n t.pretranslate(trans);\n return t.matrix();\n }\n}\n\n\nint main()\n{\n\n}\n", "meta": {"hexsha": "f128d85d5fa46904a5277b1d87fbe74175978916", "size": 10679, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry_transformation.cpp", "max_stars_repo_name": "behnamasadi/Mastering_Eigen", "max_stars_repo_head_hexsha": "99edbc819c89a4805b777eef69044a1658d96206", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-04-14T16:54:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T15:55:08.000Z", "max_issues_repo_path": "src/geometry_transformation.cpp", "max_issues_repo_name": "behnamasadi/Mastering_Eigen", "max_issues_repo_head_hexsha": "99edbc819c89a4805b777eef69044a1658d96206", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/geometry_transformation.cpp", "max_forks_repo_name": "behnamasadi/Mastering_Eigen", "max_forks_repo_head_hexsha": "99edbc819c89a4805b777eef69044a1658d96206", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-25T10:08:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-06T14:27:32.000Z", "avg_line_length": 33.0619195046, "max_line_length": 147, "alphanum_fraction": 0.5935012642, "num_tokens": 3149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567176, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7850264739984729}} {"text": "/* Main routine to run a stencil-based finite-difference method for solution of a\n second-order, scalar-valued BVP:\n\n u'' = p(t)*u' + q(t)*u + r(t), a\n#include \n#include \n#include \n#include \"bvp.hpp\"\n\nusing namespace std;\nusing namespace arma;\n\n#ifndef USE_SPARSE\n#define SPARSE_LINALG 0\n#else\n#define SPARSE_LINALG 1\n#endif\n\n// main routine\nint main(int argc, char **argv) {\n\n // get lambda from the command line, otherwise set to -10\n double lambda;\n if (argc > 1)\n lambda = atof(argv[1]);\n if (lambda >= 0.0)\n lambda = -10.0;\n\n // define BVP object\n BVP bvp(lambda);\n\n // loop over spatial resolutions for tests\n vector N = {100, 1000, 10000};\n for (int i=0; i\n#include\n\n// external math functions \n#include\n\n// common C++ head files may be used in the program\n#include\n#include\n#include\n#include \n#include\n#include\n#include\n#include\n#include\n#include\n\n#include // special functions in math\n#include \n#include \n#include \nusing namespace boost::math;\nusing namespace boost;\nusing namespace std;\n#define PI 3.1415926535897932384626E0 \n\ndouble fm(const double& a, const int& m); \ndouble doubleFac(const int& m, const int& n); \n\ndouble fm(const double& a, const int& m) {\n\tdouble x = 1.0E0;\n\tif (fabs(a)<1.0E-14) return (pow(x,2*m+1)/(2*m+1));\n\tdouble f12 = 1.0E0/2.0E0;\n\tdouble p = 1.0E0/(2.0E0*pow(a,m+f12));\n\tdouble upperLimit = a*pow(x,2.0E0);\n\treturn tgamma_lower(m+f12,upperLimit)*p;\n}\n\ndouble doubleFac(const int& m, const int& n) {\n\t// calculate (2m-1)!!/(2m+2n+1)!!\n\tdouble x = 1.0E0;\n\tfor(int i=0; i<=n; i++) {\n\t\tx *= 1.0E0/(2*m+2*i+1); \n\t}\n\treturn x;\n} \n\nint main() \n{\n\t///////////////////////////////////////////////////\n\t// global settings\n\t// step length and number of claculation for \n\t// time performance\n\t// global error is the error range\n\t// if the difference is less than the error, we \n\t// think the error could be omitted\n\t///////////////////////////////////////////////////\n\tint N = 10000000;\n\tdouble steplength = 0.000001;\n\tdouble globalError = 1.0E-14;\n\tint top_M_limmit = 40;\n\tdouble T_max_limit = 40.0E0;\n\tfloat steplength_f = 0.00001;\n\tfloat globalError_f = 1.0E-6;\n\n\t///////////////////////////////////////////////////\n\t// this section testing the timing performance\n\t// between the different functions\n\t// so far, erf is 160 faster than the fmt function\n\t// in boost library\n\t///////////////////////////////////////////////////\n\tcout << \"===========================================================\" << endl;\n\tcout << \"Time performance result: \" << endl;\n\tcout << \"Total sample number is \" << N << endl;\n\tcout << \"===========================================================\" << endl;\n\t// testing the erf\n\ttimer t1;\n\tfor(int i=0; i=0; i--) {\n\t\t\t\tdouble s = fm(T,i);\n\t\t\t\tdouble e = (1.0/(2*i+1.0))*(t2*e0+et);\n\t\t\t\tdouble d = fabs(s-e);\n\t\t\t\tif (d>globalError) {\n\t\t\t\t\tprintf(\"T is %-16.14f\\n\", T);\n\t\t\t\t\tprintf(\"for m=%d difference is %-16.14f\\n\", n, d);\n\t\t\t\t}\n\t\t\t\te0 = e;\n\t\t\t}\n\t\t}\n\t}\n\n\tcout << endl << endl;\n\tcout << \"===========================================================\" << endl;\n\tcout << \"testing the down recursive relation for m = 1 to \" << top_M_limmit << endl;\n\tcout << \"this is for float type variable\" << endl;\n\tcout << \"error range is \" << globalError_f << endl;\n\tcout << \"step length for T is \" << steplength_f << endl;\n\tcout << \"T is ranging from 0 \" << \" to \" <=0; i--) {\n\t\t\t\tfloat s = fm(T,i);\n\t\t\t\tfloat e = (1.0/(2*i+1.0))*(t2*e0+et);\n\t\t\t\tfloat d = fabs(s-e);\n\t\t\t\tif (d>globalError_f) {\n\t\t\t\t\tprintf(\"T is %-10.7f\\n\", T);\n\t\t\t\t\tprintf(\"for m=%d difference is %-10.7f\\n\", n, d);\n\t\t\t\t}\n\t\t\t\te0 = e;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "c67eab95fb37235c41f3aa44e8ff0bee73b0a0c5", "size": 5847, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "util/fmt_test/fmt_test_down.cpp", "max_stars_repo_name": "murfreesboro/cppints", "max_stars_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "util/fmt_test/fmt_test_down.cpp", "max_issues_repo_name": "murfreesboro/cppints", "max_issues_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "util/fmt_test/fmt_test_down.cpp", "max_forks_repo_name": "murfreesboro/cppints", "max_forks_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3819095477, "max_line_length": 85, "alphanum_fraction": 0.547460236, "num_tokens": 1727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7843502080174365}} {"text": "// Diagonalizing tridiagonal Toeplitz matrix with Lapack functions\n// Compile as c++ -O3 -o Tridiag.x TridiagToeplitz.cpp -larmadillo -llapack -lblas\n#include \n#include \n#include \n#include \n#include \n#include \"Tridiag.h\" \nusing namespace std;\nusing namespace arma;\n\nvec GetEigenvalues(int Dim)\n {\n int i, j;\n double RMin, RMax, Step, DiagConst, NondiagConst; \n RMin = 0.0; RMax = 1.0;\n mat Hamiltonian = zeros(Dim,Dim);\n // Integration step length\n Step = RMax/ Dim;\n DiagConst = 2.0 / (Step*Step);\n NondiagConst = -1.0 / (Step*Step);\n // Setting up tridiagonal matrix and diagonalization using Armadillo\n Hamiltonian(0,0) = DiagConst;\n Hamiltonian(0,1) = NondiagConst;\n for(i = 1; i < Dim-1; i++) {\n Hamiltonian(i,i-1) = NondiagConst;\n Hamiltonian(i,i) = DiagConst;\n Hamiltonian(i,i+1) = NondiagConst;\n }\n Hamiltonian(Dim-1,Dim-2) = NondiagConst;\n Hamiltonian(Dim-1,Dim-1) = DiagConst;\n // diagonalize and obtain eigenvalues\n vec Eigval(Dim);\n eig_sym(Eigval, Hamiltonian);\n return Eigval;\n} // end of eigenvalue function\n\n\n", "meta": {"hexsha": "4dcaebae80fb36417b0a6ebe646bb90f1a7a4e8b", "size": 1155, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/Projects/2018/Project2/CodeExample/UnitTestscpp/ToeplitzTests/Tridiag.cpp", "max_stars_repo_name": "kimrojas/ComputationalPhysicsMSU", "max_stars_repo_head_hexsha": "a47cfc18b3ad6adb23045b3f49fab18c0333f556", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 220.0, "max_stars_repo_stars_event_min_datetime": "2016-08-25T09:18:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:09:16.000Z", "max_issues_repo_path": "doc/Projects/2018/Project2/CodeExample/UnitTestscpp/ToeplitzTests/Tridiag.cpp", "max_issues_repo_name": "dnhdang94/ComputationalPhysicsMSU", "max_issues_repo_head_hexsha": "16990c74cf06eb5b933982137f0536d669567259", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-04T12:55:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-04T12:55:10.000Z", "max_forks_repo_path": "doc/Projects/2018/Project2/CodeExample/UnitTestscpp/ToeplitzTests/Tridiag.cpp", "max_forks_repo_name": "dnhdang94/ComputationalPhysicsMSU", "max_forks_repo_head_hexsha": "16990c74cf06eb5b933982137f0536d669567259", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 136.0, "max_forks_repo_forks_event_min_datetime": "2016-08-25T09:04:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T09:54:21.000Z", "avg_line_length": 29.6153846154, "max_line_length": 83, "alphanum_fraction": 0.6666666667, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966101527047, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7843405595619374}} {"text": "#include \"lrgGradientDescentSolverStrategy.h\"\n#include \n#include \n#include \n#include \n\nusing namespace Eigen;\n\n// I havent used namespaces elsewhere, but eigen reccomended it on its own page, so I used it, std is kept\n\nGradientSolver::GradientSolver(float _eta,int _iterations,float _batch_size)\n{\n eta = _eta;\n iterations = _iterations; \n batch_size = _batch_size;\n}\n\n// the inputs specified in the header file\n\nstd::pair &GradientSolver::FitData(std::vector >&Inputs,std::pair&Theta){\n\n// create the eigen matricies needed to do the linear algebra\n\n VectorXd Y_e = VectorXd::Ones(Inputs.size());\n MatrixXd M_X = MatrixXd::Ones(Inputs.size(),2); \n\n// convert the double pair vector inputs from std to eigen arrays, simply go element by element and copy them over.\n// note; the first column should be 1's and the second the actual data for M_X.\n\n for(int i=0; i < Inputs.size();++i){\n Y_e(i) = Inputs[i].second;\n M_X.col(1)(i) = Inputs[i].first;\n }\n \n MatrixXd Gradient;\n MatrixXd Theta_e = MatrixXd::Random(2,1);\n\n// the meat of the equation, note that batch_size is a float purely because you cant divide cleanly by integers.\n\n for(int k=0; k < iterations; ++k){\n Gradient = (2/batch_size) * (M_X.transpose()*((M_X*Theta_e)-Y_e));\n Theta_e = (Theta_e - (eta*Gradient));\n }\n\n Theta.first = Theta_e(1);\n Theta.second = Theta_e(0);\n \n return Theta; \n};\n\n\n\n", "meta": {"hexsha": "87c27e45e6dbe6df157b5adda844f3cb92f6db74", "size": 1528, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/Lib/lrgGradientDescentSolverStrategy.cpp", "max_stars_repo_name": "sukrire/PHAS0100Assignment1", "max_stars_repo_head_hexsha": "33013ee65f5c071a18e513ce46fc28c2de80e039", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/Lib/lrgGradientDescentSolverStrategy.cpp", "max_issues_repo_name": "sukrire/PHAS0100Assignment1", "max_issues_repo_head_hexsha": "33013ee65f5c071a18e513ce46fc28c2de80e039", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Lib/lrgGradientDescentSolverStrategy.cpp", "max_forks_repo_name": "sukrire/PHAS0100Assignment1", "max_forks_repo_head_hexsha": "33013ee65f5c071a18e513ce46fc28c2de80e039", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-16T16:41:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-16T22:13:23.000Z", "avg_line_length": 28.8301886792, "max_line_length": 131, "alphanum_fraction": 0.6812827225, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545274901875, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7838505264295339}} {"text": "#include \n#include \n\nusing namespace std;\nint main()\n{\n Eigen::MatrixXf mat(2,4);\n mat << 1, 2, 6, 9,\n 3, 1, 7, 2;\n\n std::cout << \"Column's maximum: \" << std::endl\n << mat.colwise().maxCoeff() << std::endl;\n}", "meta": {"hexsha": "590bad9804e67e712f1c3387fd707d9e42e0f072", "size": 244, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/doc/examples/Tutorial_ReductionsVisitorsBroadcasting_colwise.cpp", "max_stars_repo_name": "mathstuf/ParaView", "max_stars_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-21T20:20:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-21T20:20:59.000Z", "max_issues_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/doc/examples/Tutorial_ReductionsVisitorsBroadcasting_colwise.cpp", "max_issues_repo_name": "mathstuf/ParaView", "max_issues_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/doc/examples/Tutorial_ReductionsVisitorsBroadcasting_colwise.cpp", "max_forks_repo_name": "mathstuf/ParaView", "max_forks_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-04-14T13:42:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-22T04:59:42.000Z", "avg_line_length": 18.7692307692, "max_line_length": 48, "alphanum_fraction": 0.5655737705, "num_tokens": 89, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7838335519562238}} {"text": "/**\n * This file is part of https://github.com/adrelino/interpolation-methods\n *\n * Copyright (c) 2018 Adrian Haarbach \n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n#ifndef INTERPOL_B_SPLINE_HPP\n#define INTERPOL_B_SPLINE_HPP\n\n#include \n\nnamespace interpol {\n\nnamespace b_spline {\n\n//important: do not use c++11 auto with Eigen expressions: https://eigen.tuxfamily.org/dox/TopicPitfalls.html\n\n/**\n * Basis form\n */\nconst Eigen::Matrix4d C_basis = (Eigen::Matrix4d() << \\\n -1/6.0, 3/6.0, -3/6.0, 1/6.0,\n 3/6.0, -6/6.0, 3/6.0, 0/6.0,\n -3/6.0, 0/6.0, 3/6.0, 0/6.0,\n 1/6.0, 4/6.0, 1/6.0, 0/6.0).finished();\n\ntemplate\nEigen::Matrix spline_B_basis(double u) {\n return (Eigen::RowVector4d(u*u*u,u*u,u,1)*C_basis).cast();\n}\n\ntemplate\nEigen::Matrix spline_B_basis_dot(double u) {\n return (Eigen::RowVector4d(3*u*u,2*u,1,0)*C_basis).cast();\n}\n\ntemplate\nEigen::Matrix spline_B_basis_dotdot(double u) {\n return (Eigen::RowVector4d(6*u,2,0,0)*C_basis).cast();\n}\n\n\n/**\n * Cumulative form\n */\nconst Eigen::Matrix4d C_cumul = (Eigen::Matrix4d() << \\\n 6.0 / 6.0 , 0.0 , 0.0 , 0.0 ,\n 5.0 / 6.0 , 3.0 / 6.0 , -3.0 / 6.0 , 1.0 / 6.0 ,\n 1.0 / 6.0 , 3.0 / 6.0 , 3.0 / 6.0 , -2.0 / 6.0 ,\n 0.0 , 0.0 , 0.0 , 1.0 / 6.0).finished();\n\ntemplate\nEigen::Matrix spline_B(double u) {\n return (C_cumul*Eigen::Vector4d(1,u,u*u,u*u*u)).cast();\n}\n\ntemplate\nEigen::Matrix spline_B_dot(double u, double dt) {\n return (C_cumul*Eigen::Vector4d(0,1/dt,(2*u)/dt,(3*u*u)/dt)).cast();\n}\n\ntemplate\nEigen::Matrix spline_B_dotdot(double u, double dt) {\n double dt2 = dt * dt;\n return (C_cumul*Eigen::Vector4d(0,0,2/dt2,(6*u)/dt2)).cast();\n}\n\n} // ns b_spline\n\n} // ns interpol\n\n#endif //INTERPOL_B_SPLINE_HPP", "meta": {"hexsha": "17926f5d794deb3fd67ce22ebd5b91a469e7337c", "size": 2056, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libinterpol/include/interpol/euclidean/b_spline.hpp", "max_stars_repo_name": "adrelino/interpolation-methods", "max_stars_repo_head_hexsha": "094cbabbd0c25743d088a623f5913149c6b8a2ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 81.0, "max_stars_repo_stars_event_min_datetime": "2018-08-31T03:26:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T04:01:44.000Z", "max_issues_repo_path": "src/libinterpol/include/interpol/euclidean/b_spline.hpp", "max_issues_repo_name": "bygreencn/interpolation-methods", "max_issues_repo_head_hexsha": "508723d1bca10c350f1a83c2fd31c2227cc1c0a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-16T06:45:12.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-15T17:47:01.000Z", "max_forks_repo_path": "src/libinterpol/include/interpol/euclidean/b_spline.hpp", "max_forks_repo_name": "bygreencn/interpolation-methods", "max_forks_repo_head_hexsha": "508723d1bca10c350f1a83c2fd31c2227cc1c0a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T18:37:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T15:04:37.000Z", "avg_line_length": 27.7837837838, "max_line_length": 109, "alphanum_fraction": 0.6070038911, "num_tokens": 792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9697854111860905, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7836518016850474}} {"text": "// factorial.cpp: example program to demonstrate factorials with arbitrary precision number systems\n//\n// Copyright (C) 2017-2021 Stillwater Supercomputing, Inc.\n//\n// This file is part of the universal numbers project, which is released under an MIT Open Source license.\n#include \"common.hpp\"\n// bring in different number systems\n#include \n#include \n#define POSIT_THROW_ARITHMETIC_EXCEPTION 1\n#include \n// bring in the factorial function\n#include \n\nint main() \ntry {\n\tusing namespace std;\n\tusing namespace boost::multiprecision;\n\tusing namespace sw::function;\n\tusing namespace sw::universal;\n\n\tint N = 30;\n\tint128_t v = factorial(N);\n\tstd::cout << typeid(v).name() << \" : \\n\" << v << std::endl;\n\t \n\tcpp_int u = factorial(N);\n\tstd::cout << typeid(u).name() << \" : \\n\" << u << std::endl;\n\n\tinteger<128> w = factorial< integer<128> >(N);\n\tstd::cout << typeid(w).name() << \" : \\n\" << w << std::endl;\n\n\tusing Posit64 = posit<64, 3>;\n\tPosit64 p64 = factorial(N);\n\tcout << typeid(p64).name() << \" : \\n\" << setprecision(40) << p64 << endl;\n\n\tusing Posit128 = posit<128, 4>;\n\tPosit128 p128 = factorial(N);\n\tcout << typeid(p128).name() << \" : \\n\" << setprecision(40) << p128 << endl;\n\n\tusing Posit256 = posit<256, 4>;\n\tPosit256 p256 = factorial(N);\n\tcout << typeid(p256).name() << \" : \\n\" << setprecision(40) << p256 << endl;\n\n\treturn EXIT_SUCCESS;\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": "a11ea345615bf441dd6ab09a7c734ff76bc0e0f4", "size": 2276, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/integer/factorial.cpp", "max_stars_repo_name": "shikharvashistha/hpr-blas", "max_stars_repo_head_hexsha": "73f109d45701fc3816af0a1ecd42f11d494a6f97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-07T11:30:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-07T11:30:17.000Z", "max_issues_repo_path": "applications/integer/factorial.cpp", "max_issues_repo_name": "jamesquinlan/hpr-blas", "max_issues_repo_head_hexsha": "2975b4378b36a0bdc55d0dbd4f979163f7009678", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/integer/factorial.cpp", "max_forks_repo_name": "jamesquinlan/hpr-blas", "max_forks_repo_head_hexsha": "2975b4378b36a0bdc55d0dbd4f979163f7009678", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5142857143, "max_line_length": 106, "alphanum_fraction": 0.6792618629, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7836424710575183}} {"text": "/**\n Author: Dr. Ing. Ahmad Kamal Nasir\n Email: dringakn@gmail.com\n Description:\n Eigen Geometry module provides two different types of transformations.\n Abstract Transformation:\n Such as rotations(angle and axis, quaternions), translations, scaling.\n These transformations are not represented by matrices, never the less\n we can mix them with matrices and vectors in expressions and convert\n them to the matrices if required.\n Projective/Affine Transformation:\n These are represented by the \"Transform\" class. These are matrices.\n We can construct the Transform from abstract transformation as follows\n Transform t(AngleAxis(angle,axis))\n Note:\n Eigen default to column major storage.\n Projective transformation is the most general set of transformation.\n Affine transformation is a subset of the projective transformation.\n Euclidian transformation is a subset of the Affine transformation.\n Length, Angles and Areas are preserved in the Euclidian transformation.\n Parallel lines remain parallel in Affine transformation.\n REFERENCE:\n https://eigen.tuxfamily.org/dox/GettingStarted.html\n https://eigen.tuxfamily.org/dox/group__TutorialMatrixClass.html\n Size can be 2,3,4 for fixed size square matrices or X for dynamic size\n */\n\n#include //cout, std\n#include //Matrix\n#include //Transformation\n#include //vector\n#include //default_random_engine, uniform_real_distribution\n\n#define D2R(x) (x*M_PI/180.0)\n#define R2D(x) (x*180.0/M_PI)\n\nusing namespace std;\nusing namespace Eigen;\n\nint main() {\n\tdefault_random_engine rng;\n\tuniform_real_distribution dist(-5, 5);\n\n\t// Create Transformation object\n\tTransform t = Transform::Identity();\n\tt.scale(1);\n\tt.translate(Vector3d(1, 2, 3));\n\tt.rotate(Quaterniond(AngleAxisd(D2R(30), Vector3d::UnitZ())));\n\tcout << \"Transformation:\" << endl;\n\tcout << \"Matrix:\" << endl << t.matrix() << endl;\n\tcout << \"Translation:\" << endl << t.translation() << endl;\n\tcout << \"Rotation:\" << endl << t.rotation().eulerAngles(0, 1, 2)*R2D(1) << endl;\n\n\tconst int N = 5;\n\tMatrix pc1;\n\n\tfor (int i = 0; i < N; i++) {\n\t\t//Vector3d p1;\n\t\t//p1 << dist(rng), dist(rng), dist(rng);\n\t\t//pc1.conservativeResize(NoChange, pc1.cols() + 1);\n\t\t//pc1.col(pc1.cols() - 1) = p1;\n\t\tpc1.col(i) << dist(rng), dist(rng), dist(rng);\n\t}\n\tcout << \"pc1:\" << endl << pc1 << endl << \"---\" << endl;\n\n\t// Extract each column and convert it to a homegenous vector and transform it\n\t// After the transformation remove the last row\n\t//MatrixXd pc2 = (t * pc1.colwise().homogeneous()).block(0, 0, 3, N);\n\tMatrixXd pc2 = t * pc1.colwise().homogeneous();\n\tpc2.conservativeResize(3, NoChange);\n\tcout << \"pc2:\" << endl << pc2 << endl << \"---\" << endl;\n\n\t//Extract the mean vector for both pointclouds\n\tVector3d mu1 = pc1.rowwise().mean();\n\tVector3d mu2 = pc2.rowwise().mean();\n\tcout << \"mu1:\" << endl << mu1 << endl << \"---\" << endl;\n\tcout << \"mu2:\" << endl << mu2 << endl << \"---\" << endl;\n\n\t// Subtract the respective mean from each point in the pointcloud\n\tpc1.colwise() -= mu1;\n\tpc2.colwise() -= mu2;\n\tcout << \"pc1:\" << endl << pc1 << endl << \"---\" << endl;\n\tcout << \"pc2:\" << endl << pc2 << endl << \"---\" << endl;\n\n\t// Calculate the sum of dot products: Sum(pc1 * pc2^T)\n\tMatrix3d W = pc1 * pc2.transpose();\n\tcout << \"W:\" << endl << W << endl << \"---\" << endl;\n\n\t// Calculate the SVD of the matrix\n\tJacobiSVD svd(W, ComputeThinU | ComputeThinV);\n\tMatrixXd S = svd.singularValues();\n\tMatrixXd U = svd.matrixU();\n\tMatrixXd V = svd.matrixV();\n\tcout << \"SVD:\" << endl;\n\tcout << \"Singular Values:\" << endl << S << endl;\n\tcout << \"U:\" << endl << U << endl;\n\tcout << \"V:\" << endl << V << endl;\n\n\t// Compute rotation\n\t// R = U*V^T\n\t// t = mu_x - R*mu_p\n\n\t//Matrix3d R = U * V.transpose();\n\t//Vector3d T = mu1 - R * mu2;\n\tMatrix3d R = V * U.transpose();\n\tVector3d T = mu2 - R * mu1;\n\tcout << \"R:\" << endl << R << endl;\n\tcout << \"det(R):\" << endl << R.determinant() << endl;\n\tcout << \"Rotation:\" << endl << R.eulerAngles(0, 1, 2)*R2D(1) << endl;\n\tcout << \"Translation:\" << endl << T << endl;\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "9dbb6e5bd6a4c635dc9173575ec3eb31a7be937c", "size": 4261, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/example_iterative_closest_points_algorithm.cpp", "max_stars_repo_name": "dringakn/ROSExamples", "max_stars_repo_head_hexsha": "f4f19d21fab3630c112148e198f117f0466032c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-14T19:37:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-15T04:38:09.000Z", "max_issues_repo_path": "src/example_iterative_closest_points_algorithm.cpp", "max_issues_repo_name": "dringakn/ROSExamples", "max_issues_repo_head_hexsha": "f4f19d21fab3630c112148e198f117f0466032c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/example_iterative_closest_points_algorithm.cpp", "max_forks_repo_name": "dringakn/ROSExamples", "max_forks_repo_head_hexsha": "f4f19d21fab3630c112148e198f117f0466032c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.052173913, "max_line_length": 83, "alphanum_fraction": 0.6416334194, "num_tokens": 1198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.7835996370138697}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef unsigned long long int uint64;\ntypedef long long int int64;\n\nlong double f(double *p) {\n //return sin(p[0]) + cos(p[1]) / sqrt(p[2] + p[3] + p[4] + 1) * pow (p[5] + p[6] + p[7] + p[8] + p[9], 5);\n return sin(p[0]) + cos(p[1]);// / sqrt(p[2] + p[3] + p[4] + 1) * pow (p[5] + p[6] + p[7] + p[8] + p[9], 5);\n};\n\n\ndouble integrate(std::vector &xlow,\n std::vector &xhigh, uint64 npd)\n{\n if (xlow.size() != xhigh.size()) {\n std::cerr << \"unequal number of dimensions in xlow and xhigh\\n\";\n return NAN;\n }\n\n boost::mt19937 igen(42u);\n igen.seed(static_cast(std::time(0)));\n boost::variate_generator >\n gen(igen, boost::uniform_real<>(0, 1));\n double *point = new double [xlow.size()];\n\n double mult = 1.0;\n for(uint64 i = 0; i < xlow.size(); ++i) {\n mult = mult * (xhigh[i] - xlow[i]);\n }\n\n double sigma = 0;\n for(uint64 i = 0; i < npd * xlow.size(); ++i) {\n for (uint64 j = 0; j < xlow.size(); ++j) {\n point[j] = gen() * (xhigh[j] - xlow[j]) + xlow[j];\n // std::cout << point[j] << \" \";\n }\n // std::cout << std::endl;\n sigma += f(point);\n // std::cout << mult * sigma / (npd * xlow.size()) << \",\\n\";\n }\n\n delete [] point;\n return mult * sigma / (npd * xlow.size());\n}\n\nint main(void)\n{\n// std::vector xlow { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};\n// std::vector xhigh { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};\n std::vector xlow { 0.0, 0.0};\n std::vector xhigh { 1.0, 1.0};\n\n\n std::cout << \"I = \" << integrate(xlow, xhigh, 1000000) << std::endl;\n\n return 0;\n};\n\n", "meta": {"hexsha": "05492ce1149b37e3dc952b6e6c9f6f35bc8641b0", "size": 1907, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CompMath/montecarlo/src/montecarlo.cpp", "max_stars_repo_name": "ncos/hometasks", "max_stars_repo_head_hexsha": "9504ef7ed8fe30b5bc78ca1e423a2b85e46734a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-02-19T21:21:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-30T19:49:01.000Z", "max_issues_repo_path": "CompMath/montecarlo/src/montecarlo.cpp", "max_issues_repo_name": "ncos/hometasks", "max_issues_repo_head_hexsha": "9504ef7ed8fe30b5bc78ca1e423a2b85e46734a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CompMath/montecarlo/src/montecarlo.cpp", "max_forks_repo_name": "ncos/hometasks", "max_forks_repo_head_hexsha": "9504ef7ed8fe30b5bc78ca1e423a2b85e46734a1", "max_forks_repo_licenses": ["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.3384615385, "max_line_length": 109, "alphanum_fraction": 0.5432616675, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037221561135, "lm_q2_score": 0.8459424295406087, "lm_q1q2_score": 0.7835996212132516}} {"text": "// C++ includes\n#include \nusing namespace std;\n\n// Eigen includes\n#include \nusing namespace Eigen;\n\n// autodiff include\n#include \n#include \nusing namespace autodiff;\n\n// Define a 2nd order dual type using HigherOrderDual construct.\nusing dual2nd = HigherOrderDual<2>;\n\n// The scalar function for which the gradient is needed\ndual2nd f(const VectorXdual2nd& x)\n{\n return x.cwiseProduct(x).sum(); // sum([x(i) * x(i) for i = 1:5])\n}\n\nint main()\n{\n VectorXdual2nd x(3); // the input vector x with 3 variables\n x << 1, 2, 3; // x = [1, 2, 3]\n\n dual2nd u; // the output scalar u = f(x) evaluated together with Hessian below\n VectorXdual g;\n\n MatrixXd H = hessian(f, wrt(x), at(x), u, g); // evaluate the function value u and its Hessian matrix H\n\n cout << \"u = \" << u << endl; // print the evaluated output u\n cout << \"Hessian = \\n\" << H << endl; // print the evaluated Hessian matrix H\n cout << \"g =\\n\" << g << endl; // print the evaluated gradient vector gp = [du/dx]\n}\n", "meta": {"hexsha": "054c7a4009e8bb7075027d70ffc8283421622b11", "size": 1069, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/forward/example-forward-hessian-derivatives-using-eigen.cpp", "max_stars_repo_name": "rbharvs/autodiff", "max_stars_repo_head_hexsha": "d0305026b84c2f85f74012f312cc57bb1a894bd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-21T04:02:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T04:02:38.000Z", "max_issues_repo_path": "examples/forward/example-forward-hessian-derivatives-using-eigen.cpp", "max_issues_repo_name": "gayatri-a-b/autodiff", "max_issues_repo_head_hexsha": "98bdfea087cb67dd6e2a1a399e90bbd7ac4eb326", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-22T07:15:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-22T07:15:49.000Z", "max_forks_repo_path": "examples/forward/example-forward-hessian-derivatives-using-eigen.cpp", "max_forks_repo_name": "gayatri-a-b/autodiff", "max_forks_repo_head_hexsha": "98bdfea087cb67dd6e2a1a399e90bbd7ac4eb326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-02-26T13:14:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T03:52:45.000Z", "avg_line_length": 28.8918918919, "max_line_length": 107, "alphanum_fraction": 0.6566884939, "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109812297142, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7835776684340969}} {"text": "#include \n#include \nusing namespace std;\n\n/* Eigen part */\n#include \n#include \n\n#define MATRIX_SIZE 50\n\nint main(int argc, char** argv)\n{\n Eigen::Matrix matrix_23;\n Eigen::Vector3d v_3d;\n Eigen::Matrix3d matrix_33 = Eigen::Matrix3d::Zero();\n\n Eigen::Matrix matrix_dynamic;\n Eigen::MatrixXd matrix_x;\n\n matrix_23 << 1, 2, 3, 4, 5, 6;\n cout << matrix_23 << endl;\n\n for (int i=0; i<1; i++) {\n for (int j=0; j<2; j++) {\n cout << matrix_23(i, j) << endl;\n }\n }\n\n v_3d << 3, 2, 1;\n\n Eigen::Matrix result = matrix_23.cast() * v_3d;\n cout << result << endl;\n\n matrix_33 = Eigen::Matrix3d::Random();\n cout << matrix_33 << endl << endl;\n\n cout << matrix_33.transpose() << endl;\n cout << matrix_33.sum() << endl;\n cout << matrix_33.trace() << endl;\n cout << matrix_33 * 10 << endl;\n cout << matrix_33.inverse() << endl;\n cout << matrix_33.determinant() << endl;\n\n cout << matrix_33.inverse() << endl;\n\n Eigen::SelfAdjointEigenSolver eigen_solver(matrix_33.transpose() * matrix_33);\n cout << \"Eigen values = \" << eigen_solver.eigenvalues() << endl;\n cout << \"Eigen vectors = \" << eigen_solver.eigenvectors() << endl;\n\n Eigen::Matrix matrix_NN;\n matrix_NN = Eigen::MatrixXd::Random(MATRIX_SIZE, MATRIX_SIZE);\n Eigen::Matrix v_Nd;\n v_Nd = Eigen::MatrixXd::Random(MATRIX_SIZE, 1);\n\n clock_t time_stt = clock();\n\n Eigen::Matrix x = matrix_NN.inverse()*v_Nd;\n cout << \"time use in normal inverse is \" << 1000 * (clock() - time_stt) / (double)CLOCKS_PER_SEC << \"ms\" << endl;\n\n time_stt = clock();\n x = matrix_NN.colPivHouseholderQr().solve(v_Nd);\n cout << \"time use in normal inverse is \" << 1000 * (clock() - time_stt) / (double)CLOCKS_PER_SEC << \"ms\" << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "64e452e2a10af00d3549f161e03ba20f198b9ac5", "size": 2004, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "useEigen/eigenMatrix.cpp", "max_stars_repo_name": "LSXiang/slam_learning_journey", "max_stars_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-03-22T00:25:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-01T05:23:27.000Z", "max_issues_repo_path": "useEigen/eigenMatrix.cpp", "max_issues_repo_name": "LSXiang/slam_learning_journey", "max_issues_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "useEigen/eigenMatrix.cpp", "max_forks_repo_name": "LSXiang/slam_learning_journey", "max_forks_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3636363636, "max_line_length": 117, "alphanum_fraction": 0.619261477, "num_tokens": 613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7832836338034055}} {"text": "//\n// This program is used to study how to calculate (SS|SS)^{m}\n// for the recursive relation. Basically, it focus on the \n// fmt function:\n// f_{m}(t) = \\int^{1}_{0} u^{2m} e^{-tu^{2}} du \n// it needs the boost library to calcualte fmt\n// fenglai liu\n// Oct. 2013\n//\n// for reference, see Harris paper and the reference cited inside:\n// Harris, Frank E\n// Evaluation of GTO molecular integrals\n// International Journal of Quantum Chemistry, 1983, Vol. 23, Page 1469--1478\n//\n// note:\n// we found that the approximation of (2m-1)!!/R expression is \n// not numerical stable. Combined with down recursive relation,\n// it introduces greater error compared with other methods. \n// Therefore we finally abadon it.\n//\n//\n//\n\n// common C head files used in the program\n#include\n#include\n\n// external math functions \n#include\n\n// common C++ head files may be used in the program\n#include\n#include\n#include\n#include \n#include\n#include\n#include\n#include\n#include\n#include\n\n#include // special functions in math\n#include \n#include \n#include \nusing namespace boost::math;\nusing namespace boost;\nusing namespace std;\n#define PI 3.1415926535897932384626E0 \n\ndouble fm(const double& a, const int& m); \ndouble doubleFac(const int& m, const int& n); \n\ndouble fm(const double& a, const int& m) {\n\tdouble x = 1.0E0;\n\tif (fabs(a)<1.0E-14) return (pow(x,2*m+1)/(2*m+1));\n\tdouble f12 = 1.0E0/2.0E0;\n\tdouble p = 1.0E0/(2.0E0*pow(a,m+f12));\n\tdouble upperLimit = a*pow(x,2.0E0);\n\treturn tgamma_lower(m+f12,upperLimit)*p;\n}\n\ndouble doubleFac(const int& m, const int& n) {\n\t// calculate (2m-1)!!/(2m+2n+1)!!\n\tdouble x = 1.0E0;\n\tfor(int i=0; i<=n; i++) {\n\t\tx *= 1.0E0/(2*m+2*i+1); \n\t}\n\treturn x;\n} \n\nint main() \n{\n\t///////////////////////////////////////////////////\n\t// global settings\n\t// step length and number of claculation for \n\t// time performance\n\t// global error is the error range\n\t// if the difference is less than the error, we \n\t// think the error could be omitted\n\t///////////////////////////////////////////////////\n\tdouble steplength = 0.000001;\n\tdouble globalError = 1.0E-14;\n\tint M_limmit = 8;\n\tdouble T_max_limit = 40.0E0;\n\tdouble T_min_limit = 1.8E0;\n\tint numSteps = (T_max_limit-T_min_limit)/steplength;\n\tdouble largest = 0.0E0;\n\n\t/////////////////////////////////////////////////////////////////////\n\t// this section testing the up recursice relation for M_limit = 8 //\n\t/////////////////////////////////////////////////////////////////////\n\tcout << endl << endl;\n\tcout << \"===========================================================\" << endl;\n\tcout << \"testing the up recursive relation for m = 1 to \" << M_limmit << endl;\n\tcout << \"error range is \" << globalError << endl;\n\tcout << \"step length for T is \" << steplength << endl;\n\tcout << \"T is ranging from \" << T_min_limit << \" to \" <globalError) {\n\t\t\t\tprintf(\"m is %d, T is %-16.14f, difference is %-16.14f\\n\", i, T, d0);\n\t\t\t\tif (d>largest) largest = d;\n\t\t\t}\n\t\t\te0 = e;\n\t\t}\n\t}\n\tprintf(\"largest difference is %-16.14f\\n\", largest);\n\n\t/////////////////////////////////////////////////////////////////////\n\t// this section testing the up recursice relation for M_limit = 9 //\n\t/////////////////////////////////////////////////////////////////////\n\tcout << endl << endl;\n\tglobalError = 1.0E-13;\n\tM_limmit = 9;\n\tcout << \"===========================================================\" << endl;\n\tcout << \"testing the up recursive relation for m = 1 to \" << M_limmit << endl;\n\tcout << \"error range is \" << globalError << endl;\n\tcout << \"step length for T is \" << steplength << endl;\n\tcout << \"T is ranging from \" << T_min_limit << \" to \" <globalError) {\n\t\t\t\tprintf(\"m is %d, T is %-16.14f, difference is %-16.14f\\n\", i, T, d0);\n\t\t\t\tif (d>largest) largest = d;\n\t\t\t}\n\t\t\te0 = e;\n\t\t}\n\t}\n\tprintf(\"largest difference is %-16.14f\\n\", largest);\n\n\t/////////////////////////////////////////////////////////////////////\n\t// this section testing the up recursice relation for M_limit = 10 //\n\t/////////////////////////////////////////////////////////////////////\n\tcout << endl << endl;\n\tglobalError = 1.0E-12;\n\tM_limmit = 10;\n\tcout << \"===========================================================\" << endl;\n\tcout << \"testing the up recursive relation for m = 1 to \" << M_limmit << endl;\n\tcout << \"error range is \" << globalError << endl;\n\tcout << \"step length for T is \" << steplength << endl;\n\tcout << \"T is ranging from \" << T_min_limit << \" to \" <globalError) {\n\t\t\t\tprintf(\"m is %d, T is %-16.14f, difference is %-16.14f\\n\", i, T, d0);\n\t\t\t\tif (d>largest) largest = d;\n\t\t\t}\n\t\t\te0 = e;\n\t\t}\n\t}\n\tprintf(\"largest difference is %-16.14f\\n\", largest);\n\n\treturn 0;\n}\n", "meta": {"hexsha": "7059be56390f6a6583cb9b728299ad202e7527b8", "size": 6318, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "util/fmt_test/fmt_test_up.cpp", "max_stars_repo_name": "murfreesboro/cppints", "max_stars_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "util/fmt_test/fmt_test_up.cpp", "max_issues_repo_name": "murfreesboro/cppints", "max_issues_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "util/fmt_test/fmt_test_up.cpp", "max_forks_repo_name": "murfreesboro/cppints", "max_forks_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.90625, "max_line_length": 82, "alphanum_fraction": 0.5397277619, "num_tokens": 1850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941718, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7832836305566863}} {"text": "/* Simple program for solving the two-dimensional diffusion \n equation or Poisson equation using Jacobi's iterative method\n Note that this program does not contain a loop over the time \n dependence. It uses OpenMP to parallelize the spatial part.\n*/\n\n#include \n#include \n#include \n#include \nusing namespace std;\nusing namespace arma;\n\nint JacobiSolver(int, double, double, mat &, mat &, double);\n\nint main(int argc, char * argv[]){\n int Npoints = 100;\n double ExactSolution;\n double dx = 1.0/(Npoints-1);\n double dt = 0.25*dx*dx;\n double tolerance = 1.0e-8;\n mat A = zeros(Npoints,Npoints);\n mat q = zeros(Npoints,Npoints);\n\n int thread_num;\n omp_set_num_threads(4);\n thread_num = omp_get_max_threads ();\n cout << \" The number of processors available = \" << omp_get_num_procs () << endl ;\n cout << \" The number of threads available = \" << thread_num << endl;\n // setting up an additional source term\n for(int i = 0; i < Npoints; i++)\n for(int j = 0; j < Npoints; j++)\n q(i,j) = -2.0*M_PI*M_PI*sin(M_PI*dx*i)*sin(M_PI*dx*j);\n \n int itcount = JacobiSolver(Npoints,dx,dt,A,q,tolerance);\n \n // Testing against exact solution\n double sum = 0.0;\n for(int i = 0; i < Npoints; i++){\n for(int j=0;j < Npoints; j++){\n ExactSolution = -sin(M_PI*dx*i)*sin(M_PI*dx*j);\n sum += fabs((A(i,j) - ExactSolution));\n }\n }\n cout << setprecision(5) << setiosflags(ios::scientific);\n cout << \"Jacobi error is \" << sum/Npoints << \" in \" << itcount << \" iterations\" << endl;\n}\n\n\n// Function for setting up the iterative Jacobi solver\nint JacobiSolver(int N, double dx, double dt, mat &A, mat &q, double abstol)\n{\n int MaxIterations = 100000;\n\n \n double D = dt/(dx*dx);\n // initial guess\n mat Aold = randu(N,N); \n // Boundary conditions, all zeros\n for(int i=0; i < N; i++){\n A(0,i) = 0.0;\n A(N-1,i) = 0.0;\n A(i,0) = 0.0;\n A(i,N-1) = 0.0;\n }\n double sum = 1.0;\n int k = 0;\n // Start the iterative solver\n while (k < MaxIterations && sum > abstol){\n int i, j;\n sum = 0.0;\n // Define parallel region\n# pragma omp parallel default(shared) private (i, j) reduction(+:sum)\n {\n # pragma omp for\n for(i = 1; i < N-1; i++){\n for(j = 1; j < N-1; j++){\n\tA(i,j) = dt*q(i,j) + Aold(i,j) +\n\t D*(Aold(i+1,j) + Aold(i,j+1) - 4.0*Aold(i,j) + \n\t Aold(i-1,j) + Aold(i,j-1));\n }\n }\n for(i = 0; i < N;i++){\n for(j = 0; j < N;j++){\n\tsum += fabs(Aold(i,j)-A(i,j));\n\tAold(i,j) = A(i,j);\n }\n }\n sum /= (N*N); \n } //end parallel region\n k++;\n } //end while loop\n return k;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "6571bf1601a2f4fc2be1ed1f754a9f17ae639f2a", "size": 2626, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/Programs/LecturePrograms/programs/PDE/cpp/OpenMPdiffusion.cpp", "max_stars_repo_name": "kimrojas/ComputationalPhysicsMSU", "max_stars_repo_head_hexsha": "a47cfc18b3ad6adb23045b3f49fab18c0333f556", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 220.0, "max_stars_repo_stars_event_min_datetime": "2016-08-25T09:18:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:09:16.000Z", "max_issues_repo_path": "doc/Programs/LecturePrograms/programs/PDE/cpp/OpenMPdiffusion.cpp", "max_issues_repo_name": "dnhdang94/ComputationalPhysicsMSU", "max_issues_repo_head_hexsha": "16990c74cf06eb5b933982137f0536d669567259", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-04T12:55:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-04T12:55:10.000Z", "max_forks_repo_path": "doc/Programs/LecturePrograms/programs/PDE/cpp/OpenMPdiffusion.cpp", "max_forks_repo_name": "dnhdang94/ComputationalPhysicsMSU", "max_forks_repo_head_hexsha": "16990c74cf06eb5b933982137f0536d669567259", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 136.0, "max_forks_repo_forks_event_min_datetime": "2016-08-25T09:04:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T09:54:21.000Z", "avg_line_length": 24.3148148148, "max_line_length": 90, "alphanum_fraction": 0.5891089109, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7832836241268292}} {"text": "// translated from DFT Python code as shown in \n// https://www.youtube.com/watch?v=sX-DNi_SX-Q\n//\n// Compile:\n// g++ -g --std=c++11 -o dft dft.cpp -Ieigen\n//\n// Execute:\n// ./dft 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17\n//\n// Plot using gnuplot:\n// plot \"plot_out.txt\" using 1:2 with lines lw 3, \"plot_in.txt\" using 1:2:(0.03) with circles fill solid\n\n#include \n#include \n#include \n#include \n\nusing std::cout;\nusing namespace Eigen;\nusing std::pow;\nusing std::exp;\nusing std::ofstream;\nusing std::ostream;\n\ntypedef std::complex complex_t;\n\ncomplex_t omega( int n )\n{\n double arg = 2. * M_PI / n;\n return complex_t( cos(arg), sin(arg));\n}\n\n\nMatrixXcd omegaMatrix( int n )\n{\n complex_t om = omega(n);\n MatrixXcd m;\n m.resize( n, n);\n\n int j,k;\n for( j = 0; j < n; j++)\n for( k = 0; k < n; k++)\n m(j,k) = pow( om, -k * j );\n \n return m / n;\n}\n\n\nVectorXcd DFT( VectorXcd Y )\n{\n int n = Y.size();\n int start = (int)ceil( ((double)n) / 2. ) - 1;\n complex_t oms = pow( omega(n), (double)start);\n \n for( int k = 0; k < n; k++)\n Y[k] *= pow( oms, (double)k);\n \n VectorXcd res;\n res = omegaMatrix( n ) * Y;\n \n for( int k = 0; k < res.size(); k++)\n res[k] *= pow( -1., k + start);\n\n return res;\n}\n\n\nvoid print_input( const VectorXcd &Y, ostream &os)\n{\n int n = Y.size();\n \n for( int k = 0; k < n; k++)\n os << (-M_PI + 2. * k * M_PI / n) << \" \" << Y[k].real() << \"\\n\";\n}\n\n\nvoid print_DFTPoly( const VectorXcd &Y, double step_x, ostream &os)\n{\n int n = Y.size();\n \n VectorXcd coeffs = DFT( Y );\n\n int zero = (n - 1) / 2;\n \n for( double x = -M_PI; x <= M_PI; x += step_x)\n {\n double S = coeffs[zero].real();\n for( int k = 1; k < (int)ceil( ((double)n) / 2.); k++)\n {\n S += cos(k * x) * (coeffs[zero-k] + coeffs[zero+k]).real();\n S += sin(k * x) * (coeffs[zero-k] - coeffs[zero+k]).imag();\n }\n \n if( n % 2 == 0 )\n S += cos(n * x / 2.) * coeffs[coeffs.size()-1].real();\n \n os << x << \" \" << S << \"\\n\";\n }\n}\n\n\nint main( int argc, char **argv)\n{\n VectorXcd in;\n\n int n = argc - 1;\n\n if( n < 3 )\n {\n std::cerr << \"input too small\\n\";\n return 1;\n }\n \n in.resize(n);\n\n for( int i = 0; i < n; i++)\n in(i) = atof( argv[i+1] );\n \n ofstream plot_in( \"plot_in.txt\" );\n ofstream plot_out( \"plot_out.txt\" );\n print_input( in, plot_in);\n print_DFTPoly( in, 0.01, plot_out);\n \n return 0;\n}\n", "meta": {"hexsha": "44d4990398fa658244dddd98b4d1c6023dc575cc", "size": 2647, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dft.cpp", "max_stars_repo_name": "mcjurij/funwitheigen", "max_stars_repo_head_hexsha": "7bd85f0e9f791ffeb392e99d50e699671ba214a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dft.cpp", "max_issues_repo_name": "mcjurij/funwitheigen", "max_issues_repo_head_hexsha": "7bd85f0e9f791ffeb392e99d50e699671ba214a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dft.cpp", "max_forks_repo_name": "mcjurij/funwitheigen", "max_forks_repo_head_hexsha": "7bd85f0e9f791ffeb392e99d50e699671ba214a9", "max_forks_repo_licenses": ["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.0079365079, "max_line_length": 104, "alphanum_fraction": 0.5001888931, "num_tokens": 935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7832836208801103}} {"text": "#include \"renderer_math_cpu.h\"\n#include \n#include \n\nEigen::MatrixXd RendererMathCpu::createCompanionMatrix(\n\tconst Eigen::VectorXd& coefficients)\n{\n\tEigen::Index N = coefficients.size() - 1;\n\tEigen::MatrixXd m = Eigen::MatrixXd::Zero(N, N);\n\n\t//diagonal, 1 below diagonal\n\tfor (Eigen::Index i = 0; i < N - 1; ++i)\n\t\tm(i + 1, i) = 1;\n\n\t//add coefficients in the first row\n\t//scaled by 1/c[0], the highest degree\n\tfor (Eigen::Index i = 0; i < N; ++i)\n\t\tm(0, i) = -coefficients[i + 1] / coefficients[0];\n\n\treturn m;\n}\n\nEigen::VectorXcd RendererMathCpu::rootsFromCompanionMatrix(const Eigen::MatrixXd& m)\n{\n\tEigen::EigenSolver es(m, false);\n\tEigen::VectorXcd eigenvalues = es.eigenvalues();\n\treturn eigenvalues;\n}\n\nstd::vector RendererMathCpu::extractRealRoots(const Eigen::VectorXcd& complexRoots, double epsilon)\n{\n\tstd::vector realRoots;\n\trealRoots.reserve(complexRoots.size());\n\tfor (Eigen::Index i=0; i\n using boost::math::students_t; // Probability of students_t(df, t).\n\n#include \n using std::cout; using std::endl;\n#include \n using std::setprecision; using std::setw;\n#include \n using std::sqrt;\n\n// This example of a two-sided test is from:\n// B. M. Smith & M. B. Griffiths, Analyst, 1982, 107, 253,\n// from Statistics for Analytical Chemistry, 3rd ed. (1994), pp 58-59\n// J. C. Miller and J. N. Miller, Ellis Horwood ISBN 0 13 0309907\n\n// Concentrations of lead (ug/l) determined by two different methods\n// for each of four test portions,\n// the concentration of each portion is significantly different,\n// the values may NOT be pooled.\n// (Called a 'paired test' by Miller and Miller\n// because each portion analysed has a different concentration.)\n\n// Portion Wet oxidation Direct Extraction\n// 1 71 76\n// 2 61 68\n// 3 50 48\n// 4 60 57\n\nconst int portions = 4;\nconst int methods = 2;\nfloat data [portions][methods] = {{71, 76}, {61,68}, {50, 48}, {60, 57}};\nfloat diffs[portions];\n\nint main()\n{\n cout << \"Example3 using Student's t function. \" << endl;\n float mean_diff = 0.f;\n cout << \"\\n\"\"Portion wet_oxidation Direct_extraction difference\" << endl;\n for (int portion = 0; portion < portions; portion++)\n { // Echo data and differences.\n diffs[portion] = data[portion][0] - data[portion][1];\n mean_diff += diffs[portion];\n cout << setw(4) << portion << ' ' << setw(14) << data[portion][0] << ' ' << setw(18)<< data[portion][1] << ' ' << setw(9) << diffs[portion] << endl;\n }\n mean_diff /= portions;\n cout << \"Mean difference = \" << mean_diff << endl; // -1.75\n\n float sd_diffs = 0.f;\n for (int portion = 0; portion < portions; portion++)\n { // Calculate standard deviation of differences.\n sd_diffs +=(diffs[portion] - mean_diff) * (diffs[portion] - mean_diff);\n }\n int degrees_of_freedom = portions-1; // Use the n-1 formula.\n sd_diffs /= degrees_of_freedom;\n sd_diffs = sqrt(sd_diffs);\n cout << \"Standard deviation of differences = \" << sd_diffs << endl; // 4.99166\n // Standard deviation of differences = 4.99166\n double t = mean_diff * sqrt(static_cast(portions))/ sd_diffs; // -0.70117\n cout << \"Student's t = \" << t << \", if \" << degrees_of_freedom << \" degrees of freedom.\" << endl;\n // Student's t = -0.70117, if 3 degrees of freedom.\n cout << \"Probability of the means being different is \"\n << 2.F * cdf(students_t(degrees_of_freedom), t) << \".\"<< endl; // 0.266846 * 2 = 0.533692\n // Double the probability because using a 'two-sided test' because\n // mean for 'Wet oxidation' could be either\n // greater OR LESS THAN for 'Direct extraction'.\n\n return 0;\n} // int main()\n\n/*\n\nOutput is:\n\nExample3 using Student's t function. \nPortion wet_oxidation Direct_extraction difference\n 0 71 76 -5\n 1 61 68 -7\n 2 50 48 2\n 3 60 57 3\nMean difference = -1.75\nStandard deviation of differences = 4.99166\nStudent's t = -0.70117, if 3 degrees of freedom.\nProbability of the means being different is 0.533692.\n\n*/\n\n\n\n\n", "meta": {"hexsha": "289daec09ed29004bd8f3cd216d1b11d9bd2031f", "size": 4706, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/math/example/students_t_example3.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/math/example/students_t_example3.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/math/example/students_t_example3.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 38.8925619835, "max_line_length": 154, "alphanum_fraction": 0.6540586485, "num_tokens": 1274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092415, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7828090344301706}} {"text": "#include \n#include \n\nusing namespace Upp;\n\nusing namespace Eigen;\n\nvoid NonLinearTests();\nvoid FFTTests();\n\nstruct SerialTest {\n\tMatrixXd m;\n\tVectorXd v;\n\tSerialTest() : m(2, 2), v(3){}\n\tvoid Print() {\n\t\tCout() << \"\\nHere is the matrix:\\n\" << m;\n\t\tCout() << \"\\nHere is the vector:\\n\" << v;\n\t}\n\tvoid Serialize(Stream& stream) {\n\t\t::Serialize(stream, m);\n\t\t::Serialize(stream, v);\n\t}\n\tvoid Jsonize(JsonIO &jio) {\n\t\tjio(\"matrix\", m)(\"vector\", v);\n\t}\n\tvoid Xmlize(XmlIO &xml) {\n\t\txml(\"matrix\", m)(\"vector\", v);\n\t}\n};\n\t\t\nCONSOLE_APP_MAIN\n{\n\tStdLogSetup(LOG_COUT|LOG_FILE);\n\t\n\tUppLog() << \"Eigen library demo\";\n\t\n\t// https://eigen.tuxfamily.org/dox/group__TutorialMatrixClass.html\n\tUppLog() << \"\\n\\nTutorial page 1 - The Matrix class\";\n\t\n\tUppLog() << \"\\n\\nCoefficient accessors\";\n\t{\n\t\tMatrixXd m(2,2);\n\t\tm(0,0) = 3;\n\t\tm(1,0) = 2.5;\n\t\tm(0,1) = -1;\n\t\tm(1,1) = m(1,0) + m(0,1);\n\t\tUppLog() << \"\\nHere is the matrix m:\\n\" << m;\n\t\t\n\t\tVectorXd v(2);\n\t\tv(0) = 4;\n\t\tv(1) = v(0) - 1;\n\t\tUppLog() << \"\\nHere is the vector v:\\n\" << v;\n\t}\n\tUppLog() << \"\\n\\nResizing\";\n\t{\n\t\tMatrixXd m(2,5);\n\t\tm.resize(4,3);\n\t\tUppLog() << \"\\nThe matrix m is of size \" << m.rows() << \"x\" << m.cols();\n\t\tUppLog() << \"\\nIt has \" << m.size() << \" coefficients\";\n\n\t\tVectorXd v(2);\n\t\tv.resize(5);\n\t\tUppLog() << \"\\nThe vector v is of size \" << v.size();\n\t\tUppLog() << \"\\nAs a matrix, v is of size \" << v.rows() << \"x\" << v.cols();\n\t}\n\tUppLog() << \"\\n\\nAssignment and resizing\";\n\t{\n\t\tdouble _dat[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17};// Assignment from C vector\n\t\tVectorXd dat = Map(_dat, sizeof(_dat)/sizeof(double)); \n\t\tUppLog() << \"\\nC array data is \" << dat.transpose();\n\t\t\n\t\tconst int dec = 5;\n \tVectorXd decimated = Map>(dat.data(), 1+((dat.size()-1)/dec));\n \tUppLog() << \"\\nDecimated \" << decimated.transpose();\n\t\t\n\t\tVectorXd even = Map>(dat.data(), (dat.size()+1)/2);\n\t\tUppLog() << \"\\nEven \" << even.transpose();\n\t\t\n\t\tVectorXd odd = Map>(dat.data()+1, dat.size()/2);\n\t\tUppLog() << \"\\nOdd \" << odd.transpose();\n\t\n\t\tMatrixXf a(2,2);\n\t\tUppLog() << \"\\na is of size \" << a.rows() << \"x\" << a.cols();\n\t\tMatrixXf b(3,3);\n\t\ta = b;\n\t\tUppLog() << \"\\na is now of size \" << a.rows() << \"x\" << a.cols();\n\t}\n\t\n\t// https://eigen.tuxfamily.org/dox-devel/group__TutorialMatrixArithmetic.html\n\tUppLog() << \"\\n\\nTutorial page 2 - Matrix and vector arithmetic\";\n\t\n\tUppLog() << \"\\n\\nAddition and subtraction\";\n\t{\n\t\tMatrix2d a;\n\t\ta << 1, 2,\n\t\t 3, 4;\n\t\tMatrixXd b(2,2);\n\t\tb << 2, 3,\n\t\t 1, 4;\n\n\t\tUppLog() << \"\\na + b =\\n\" << a + b;\n\t\tUppLog() << \"\\na - b =\\n\" << a - b;\n\t\tUppLog() << \"\\nDoing a += b;\";\n\t\ta += b;\n\t\tUppLog() << \"\\nNow a =\\n\" << a;\n\n\t\tVector3d v(1,2,3);\n\t\tVector3d w(1,0,0);\n\t\tUppLog() << \"\\n-v + w - v =\\n\" << -v + w - v;\n\t}\n\tUppLog() << \"\\n\\nScalar multiplication and division\";\n\t{\n\t\tMatrix2d a;\n\t\ta << 1, 2,\n\t\t 3, 4;\n\t\tVector3d v(1,2,3);\n\t\tUppLog() << \"\\na * 2.5 =\\n\" << a * 2.5;\n\t\tUppLog() << \"\\n0.1 * v =\\n\" << 0.1 * v;\n\t\tUppLog() << \"\\nDoing v *= 2;\";\n\t\tv *= 2;\n\t\tUppLog() << \"\\nNow v =\\n\" << v;\n\t}\n\tUppLog() << \"\\n\\nTransposition and conjugation\";\n\t{\n\t\tMatrixXcf a = MatrixXcf::Random(2,2);\n\t\tUppLog() << \"\\nHere is the matrix a\\n\" << a;\n\t\tUppLog() << \"\\nHere is the matrix a^T\\n\" << a.transpose();\n\t\tUppLog() << \"\\nHere is the conjugate of a\\n\" << a.conjugate();\n\t\tUppLog() << \"\\nHere is the matrix a^*\\n\" << a.adjoint();\n\t\t\n\t\tVectorXd v(5);\n\t\tv << 1, 2, 3, 4, 5;\n\t\tUppLog() << \"\\n\\nInitial vector \" << v.transpose();\n\t\tUppLog() << \"\\nReversed vector \" << v.reverse().transpose();\n\t}\n\tUppLog() << \"\\n\\nMatrix-matrix and matrix-vector multiplication\";\n\t{\n\t\tMatrix2d mat;\n\t\tmat << 1, 2,\n\t\t 3, 4;\n\t\tVector2d u(-1,1), v(2,0);\n\t\tUppLog() << \"\\nHere is mat*mat:\\n\" << mat*mat;\n\t\tUppLog() << \"\\nHere is mat*u:\\n\" << mat*u;\n\t\tUppLog() << \"\\nHere is u^T*mat:\\n\" << u.transpose()*mat;\n\t\tUppLog() << \"\\nHere is u^T*v:\\n\" << u.transpose()*v;\n\t\tUppLog() << \"\\nHere is u*v^T:\\n\" << u*v.transpose();\n\t\tUppLog() << \"\\nLet's multiply mat by itself\";\n\t\tmat *= mat;\n\t\tUppLog() << \"\\nNow mat is mat:\\n\" << mat;\n\t}\n\tUppLog() << \"\\n\\nDot product and cross product\";\n\t{\n\t\tVector3d v(1,2,3);\n\t \tVector3d w(0,1,2);\n\t\n\t \tUppLog() << \"\\nDot product: \" << v.dot(w);\n\t \tdouble dp = v.adjoint()*w; // automatic conversion of the inner product to a scalar\n\t \tUppLog() << \"\\nDot product via a matrix product: \" << dp;\n\t \tUppLog() << \"\\nCross product:\\n\" << v.cross(w);\n\t}\n\tUppLog() << \"\\n\\nBasic arithmetic reduction operations\";\n\t{\n\t\tEigen::Matrix2d mat;\n\t\tmat << 1, 2,\n\t\t 3, 4;\n\t\tUppLog() << \"\\nHere is mat.sum(): \" << mat.sum();\n\t\tUppLog() << \"\\nHere is mat.prod(): \" << mat.prod();\n\t\tUppLog() << \"\\nHere is mat.mean(): \" << mat.mean();\n\t\tUppLog() << \"\\nHere is mat.minCoeff(): \" << mat.minCoeff();\n\t\tUppLog() << \"\\nHere is mat.maxCoeff(): \" << mat.maxCoeff();\n\t\tUppLog() << \"\\nHere is mat.trace(): \" << mat.trace();\n\t\t\n\t\tMatrix3f m = Matrix3f::Random();\n\t\tptrdiff_t i, j;\n\t\tfloat minOfM = m.minCoeff(&i, &j);\n\t\tUppLog() << \"\\nHere is the matrix m:\\n\" << m;\n\t\tUppLog() << \"\\nIts minimum coefficient (\" << minOfM \n\t\t << \") is at position (\" << i << \",\" << j << \")\\n\";\n\t\t\n\t\tRowVector4i v = RowVector4i::Random();\n\t\tptrdiff_t maxOfV = v.maxCoeff(&i);\n\t\tUppLog() << \"\\nHere is the vector v: \" << v;\n\t\tUppLog() << \"\\nIts maximum coefficient (\" << maxOfV \n\t\t\t << \") is at position \" << i;\n\t}\n\t\n\t// https://eigen.tuxfamily.org/dox/group__TutorialArrayClass.html\n\tUppLog() << \"\\n\\nTutorial page 3 - The Array class and coefficient-wise operations \";\n\t\n\tUppLog() << \"\\n\\nAccessing values inside an Array\";\n\t{\n\t\tArrayXXf m(2,2);\n\t\t\n\t\t// assign some values coefficient by coefficient\n\t\tm(0,0) = 1.0; m(0,1) = 2.0;\n\t\tm(1,0) = 3.0; m(1,1) = m(0,1) + m(1,0);\n\t\t\n\t\t// print values to standard output\n\t\tUppLog() << \"\\n\" << m;\n\t\t\n\t\t// using the comma-initializer is also allowed\n\t\tm << 1.0,2.0,\n\t\t \t 3.0,4.0;\n\t\t \n\t\t// print values to standard output\n\t\tUppLog() << \"\\n\" << m;\n\t}\n\tUppLog() << \"\\n\\nAddition and subtraction\";\n\t{\n\t\tArrayXXf a(3,3);\n\t\tArrayXXf b(3,3);\n\t\ta << 1,2,3,\n\t\t \t 4,5,6,\n\t\t \t 7,8,9;\n\t\tb << 1,2,3,\n\t\t \t 1,2,3,\n\t\t \t 1,2,3;\n\t\t \n\t\t// Adding two arrays\n\t\tUppLog() << \"\\na + b = \" << \"\\n\" << a + b;\n\t\t\n\t\t// Subtracting a scalar from an array\n\t\tUppLog() << \"\\na - 2 = \" << \"\\n\" << a - 2;\n\t}\n\tUppLog() << \"\\n\\nArray multiplication\";\n\t{\n\t\tArrayXXf a(2,2);\n\t\tArrayXXf b(2,2);\n\t\ta << 1,2,\n\t\t \t 3,4;\n\t\tb << 5,6,\n\t\t \t 7,8;\n\t\tUppLog() << \"\\na * b = \" << \"\\n\" << a * b;\n\t}\n\tUppLog() << \"\\n\\nOther coefficient-wise operations\";\n\t{\n\t\tArrayXf a = ArrayXf::Random(5);\n\t\ta *= 2;\n\t\tUppLog() << \"\\na =\" << \"\\n\" << a;\n\t\tUppLog() << \"\\na.abs() =\" << \"\\n\" << a.abs();\n\t\tUppLog() << \"\\na.abs().sqrt() =\" << \"\\n\" << a.abs().sqrt();\n\t\tUppLog() << \"\\na.min(a.abs().sqrt()) =\" << \"\\n\" << a.min(a.abs().sqrt());\n\t}\n\tUppLog() << \"\\n\\nConverting between array and matrix expressions\";\n\t{\n\t\tMatrixXf m(2,2);\n\t\tMatrixXf n(2,2);\n\t\tm << 1,2,\n\t\t \t 3,4;\n\t\tn << 5,6,\n\t\t \t 7,8;\n\t\t\n\t\tUppLog() << \"\\n-- Matrix m*n: --\" << \"\\n\" << m * n;\n\t\tUppLog() << \"\\n-- Array m*n: --\" << \"\\n\" << m.array() * n.array();\n\t\tUppLog() << \"\\n-- With cwiseProduct: --\" << \"\\n\" << m.cwiseProduct(n);\n\t\tUppLog() << \"\\n-- Array m + 4: --\" << \"\\n\" << m.array() + 4;\n\t}\n\t{\n\t\tMatrixXf m(2,2);\n\t\tMatrixXf n(2,2);\n\t\tm << 1,2,\n\t\t 3,4;\n\t\tn << 5,6,\n\t\t 7,8;\n\t\t\n\t\tUppLog() << \"\\n-- Combination 1: --\" << \"\\n\" << (m.array() + 4).matrix() * m;\n\t\tUppLog() << \"\\n-- Combination 2: --\" << \"\\n\" << (m.array() * n.array()).matrix() * m;\n\t}\n\t\n\t// https://eigen.tuxfamily.org/dox/group__TutorialBlockOperations.html\n\tUppLog() << \"\\n\\nTutorial page 4 - Block operations\";\n\t\n\tUppLog() << \"\\n\\nUsing block operations\";\n\t{\n\t\tEigen::MatrixXf m(4,4);\n\t\tm << 1, 2, 3, 4,\n\t\t 5, 6, 7, 8,\n\t\t 9,10,11,12,\n\t\t \t 13,14,15,16;\n\t\tUppLog() << \"\\nBlock in the middle\\n\";\n\t\tUppLog() << m.block<2,2>(1,1);\n\t\tfor (ptrdiff_t i = 1; i <= 3; ++i) {\n\t\t\tUppLog() << \"\\nBlock of size \" << i << \"x\" << i << \"\\n\";\n\t\t\tUppLog() << m.block(0, 0, i, i);\n\t\t}\n\t}\n\t{\n\t\tArray22d m;\n\t\tm << 1,2,\n\t\t \t 3,4;\n\t\tArray44d a = Array44d::Constant(0.6);\n\t\tUppLog() << \"\\nHere is the array a:\\n\" << a;\n\t\ta.block<2,2>(1,1) = m;\n\t\tUppLog() << \"\\nHere is now a with m copied into its central 2x2 block:\\n\" << a;\n\t\ta.block(0,0,2,3) = a.block(2,1,2,3);\n\t\tUppLog() << \"\\nHere is now a with bottom-right 2x3 block copied into top-left 2x2 block:\\n\" << a;\n\t}\n\tUppLog() << \"\\n\\nColumns and rows\";\n\t{\n\t\tEigen::MatrixXf m(3,3);\n\t\tm << 1,2,3,\n\t\t\t 4,5,6,\n\t\t \t 7,8,9;\n\t\tUppLog() << \"\\nHere is the matrix m:\\n\" << m;\n\t\tUppLog() << \"\\n2nd Row: \" << m.row(1);\n\t\tm.col(2) += 3 * m.col(0);\n\t\tUppLog() << \"\\nAfter adding 3 times the first column into the third column, the matrix m is:\\n\";\n\t\tUppLog() << m;\n\t}\n\tUppLog() << \"\\n\\nCorner-related operations\";\n\t{\n\t\tEigen::Matrix4f m;\n\t\tm << 1, 2, 3, 4,\n\t\t \t 5, 6, 7, 8,\n\t\t \t 9, 10,11,12,\n\t\t \t 13,14,15,16;\n\t\tUppLog() << \"\\nm.leftCols(2) =\\n\" << m.leftCols(2);\n\t\tUppLog() << \"\\nm.bottomRows<2>() =\\n\" << m.bottomRows<2>();\n\t\tm.topLeftCorner(1,3) = m.bottomRightCorner(3,1).transpose();\n\t\tUppLog() << \"\\nAfter assignment, m = \\n\" << m;\n\t}\n\tUppLog() << \"\\n\\nBlock operations for vectors. Get a segment or fragment\";\n\t{\n\t\tEigen::ArrayXf v(6);\n\t\tv << 1, 2, 3, 4, 5, 6;\n\t\tUppLog() << \"\\nv.head(3) =\\n\" << v.head(3);\n\t\tUppLog() << \"\\nv.tail<3>() = \\n\" << v.tail<3>();\n\t\tv.segment(1,4) *= 2;\n\t\tUppLog() << \"\\nafter 'v.segment(1,4) *= 2', v =\\n\" << v;\n\t}\n\t\n\t// https://eigen.tuxfamily.org/dox/group__TutorialAdvancedInitialization.html\n\tUppLog() << \"\\n\\nTutorial page 5 - Advanced initialization\";\n\n\tUppLog() << \"\\n\\nThe comma initializer\";\n\t{\n\t\tRowVectorXd vec1(3);\n\t\tvec1 << 1, 2, 3;\n\t\tUppLog() << \"\\nvec1 = \" << vec1;\n\t\t\n\t\tRowVectorXd vec2(4);\n\t\tvec2 << 1, 4, 9, 16;\n\t\tUppLog() << \"\\nvec2 = \" << vec2;\n\t\t\n\t\tRowVectorXd joined(7);\n\t\tjoined << vec1, vec2;\n\t\tUppLog() << \"\\njoined = \" << joined;\n\t\t\n\t\tMatrixXf matA(2, 2);\n\t\tmatA << 1, 2, 3, 4;\n\t\tMatrixXf matB(4, 4);\n\t\tmatB << matA, matA/10, matA/10, matA;\n\t\tUppLog() << matB;\n\t\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\tUppLog() << m;\n\t}\n\tUppLog() << \"\\n\\nSpecial matrices and arrays\";\n\t{\n\t\tUppLog() << \"\\nA fixed-size array:\\n\";\n\t\tArray33f a1 = Array33f::Zero();\n\t\tUppLog() << a1 << \"\\n\\n\";\n\t\t\n\t\tUppLog() << \"\\nA one-dimensional dynamic-size array:\\n\";\n\t\tArrayXf a2 = ArrayXf::Zero(3);\n\t\tUppLog() << a2 << \"\\n\\n\";\n\t\t\n\t\tUppLog() << \"\\nA two-dimensional dynamic-size array:\\n\";\n\t\tArrayXXf a3 = ArrayXXf::Zero(3, 4);\n\t\tUppLog() << a3 << \"\\n\";\n\t\t\n\t\tUppLog() << \"\\nA two-dimensional dynamic-size array set to 1.23:\\n\";\n\t\tMatrixXd a4 = MatrixXd::Constant(3, 4, 1.23);\n\t\tUppLog() << a4 << \"\\n\";\n\t\t\n\t\tArrayXXd table(10, 4);\n\t\ttable.col(0) = ArrayXd::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\tUppLog() << \"\\n Degrees Radians Sine Cosine\\n\";\n\t\tUppLog() << table;\n\t\t\n\t\tconst ptrdiff_t size = 6;\n\t\tMatrixXd mat1(size, size);\n\t\tmat1.topLeftCorner(size/2, size/2) = MatrixXd::Zero(size/2, size/2);\n\t\tmat1.topRightCorner(size/2, size/2) = MatrixXd::Identity(size/2, size/2);\n\t\tmat1.bottomLeftCorner(size/2, size/2) = MatrixXd::Identity(size/2, size/2);\n\t\tmat1.bottomRightCorner(size/2, size/2) = MatrixXd::Zero(size/2, size/2);\n\t\tUppLog() << \"\\n\" << mat1;\n\t\t\n\t\tMatrixXd mat2(size, size);\n\t\tmat2.topLeftCorner(size/2, size/2).setZero();\n\t\tmat2.topRightCorner(size/2, size/2).setIdentity();\n\t\tmat2.bottomLeftCorner(size/2, size/2).setIdentity();\n\t\tmat2.bottomRightCorner(size/2, size/2).setZero();\n\t\tUppLog() << \"\\n\" << mat2;\n\t\t\n\t\tMatrixXd mat3(size, size);\n\t\tmat3 << MatrixXd::Zero(size/2, size/2), MatrixXd::Identity(size/2, size/2),\n\t\t MatrixXd::Identity(size/2, size/2), MatrixXd::Zero(size/2, size/2);\n\t\tUppLog() << \"\\n\" << mat3;\n\t}\n\tUppLog() << \"\\n\\nUsage as temporary objects\";\n\t{\n\t\tMatrixXd m = MatrixXd::Random(3,3);\n\t\tm = (m + MatrixXd::Constant(3,3,1.2)) * 50;\n\t\tUppLog() << \"\\nm =\\n\" << m;\n\t\tVectorXd v(3);\n\t\tv << 1, 2, 3;\n\t\tUppLog() << \"\\nm * v =\\n\" << m * v;\n\t}\n\t{\n\t\tMatrixXf mat = MatrixXf::Random(2, 3);\n\t\tUppLog() << mat;\n\t\tmat = (MatrixXf(2,2) << 0, 1, 1, 0).finished() * mat;\n\t\tUppLog() << mat;\n\t}\n\t\n\t// https://eigen.tuxfamily.org/dox/group__TutorialLinearAlgebra.html\n\tUppLog() << \"\\n\\nTutorial page 6 - Linear algebra and decompositions\";\n\n\tUppLog() << \"\\n\\nBasic linear solving\tAx = b\";\n\t{\n\t\tMatrix3f A;\n\t\tVector3f b;\n\t\tA << 1, 2, 3, \n\t\t\t 4, 5, 6, \n\t\t\t 7, 8,10;\n\t\tb << 3, 3, 4;\n\t\tUppLog() << \"\\nHere is the matrix A:\\n\" << A;\n\t\tUppLog() << \"\\nHere is the vector b:\\n\" << b;\n\t\tVector3f x = A.colPivHouseholderQr().solve(b);\n\t\tUppLog() << \"\\nThe solution is:\\n\" << x;\n\t}\n\t{\n\t\tMatrix2f A, b;\n\t\tA << 2, -1, -1, 3;\n\t\tb << 1, 2, 3, 1;\n\t\tUppLog() << \"\\nHere is the matrix A:\\n\" << A;\n\t\tUppLog() << \"\\nHere is the right hand side b:\\n\" << b;\n\t\tMatrix2f x = A.ldlt().solve(b);\n\t\tUppLog() << \"\\nThe solution is:\\n\" << x;\n\t}\n\tUppLog() << \"\\n\\nChecking if a solution really exists\";\n\t{\n\t\tMatrixXd A = MatrixXd::Random(100,100);\n\t\tMatrixXd b = MatrixXd::Random(100,50);\n\t\tMatrixXd x = A.fullPivLu().solve(b);\n\t\tdouble relative_error = (A*x - b).norm() / b.norm(); // norm() is L2 norm\n\t\tUppLog() << \"\\nThe relative error is:\\n\" << relative_error;\n\t}\n\tUppLog() << \"\\n\\nComputing eigenvalues and eigenvectors\";\n\t{\n\t\tMatrix2f A;\n\t\tA << 1, 2, 2, 3;\n\t\tUppLog() << \"\\nHere is the matrix A:\\n\" << A;\n\t\tSelfAdjointEigenSolver eigensolver(A);\n\t\tUppLog() << \"\\nThe eigenvalues of A are:\\n\" << eigensolver.eigenvalues();\n\t\tUppLog() << \"\\nHere's a matrix whose columns are eigenvectors of A \"\n\t\t << \"corresponding to these eigenvalues:\\n\"\n\t\t << eigensolver.eigenvectors();\n\t}\n\tUppLog() << \"\\n\\nComputing inverse and determinant\";\n\t{\n\t\tMatrix3f A;\n\t\tA << 1, 2, 1,\n\t\t 2, 1, 0,\n\t\t -1, 1, 2;\n\t\tUppLog() << \"\\nHere is the matrix A:\\n\" << A;\n\t\tUppLog() << \"\\nThe determinant of A is \" << A.determinant();\n\t\tUppLog() << \"\\nThe inverse of A is:\\n\" << A.inverse();\n\t}\n\tUppLog() << \"\\n\\nLeast squares solving\";\n\t{\n\t\tMatrixXf A = MatrixXf::Random(5, 2);\n\t\tUppLog() << \"\\nHere is the matrix A:\\n\" << A;\n\t\tVectorXf b = VectorXf::Random(5);\n\t\tUppLog() << \"\\nHere is the right hand side b:\\n\" << b;\n\t\tUppLog() << \"\\nThe least-squares solution is:\\n\"\n\t\t << A.jacobiSvd(ComputeThinU | ComputeThinV).solve(b);\n\t}\n\tUppLog() << \"\\n\\nSeparating the computation from the construction\";\n\t{\n\t\tMatrix2f A, b;\n\t\tLLT llt;\n\t\tA << 2, -1, -1, 3;\n\t\tb << 1, 2, 3, 1;\n\t\tUppLog() << \"\\nHere is the matrix A:\\n\" << A;\n\t\tUppLog() << \"\\nHere is the right hand side b:\\n\" << b;\n\t\tUppLog() << \"\\nComputing LLT decomposition...\";\n\t\tllt.compute(A);\n\t\tUppLog() << \"\\nThe solution is:\\n\" << llt.solve(b);\n\t\tA(1,1)++;\n\t\tUppLog() << \"\\nThe matrix A is now:\\n\" << A;\n\t\tUppLog() << \"\\nComputing LLT decomposition...\";\n\t\tllt.compute(A);\n\t\tUppLog() << \"\\nThe solution is now:\\n\" << llt.solve(b);\n\t}\n\tUppLog() << \"\\n\\nRank-revealing decompositions\";\n\t{\n\t\tMatrix3f A;\n\t\tA << 1, 2, 5,\n\t\t 2, 1, 4,\n\t\t 3, 0, 3;\n\t\tUppLog() << \"\\nHere is the matrix A:\\n\" << A;\n\t\tFullPivLU lu_decomp(A);\n\t\tUppLog() << \"\\nThe rank of A is \" << lu_decomp.rank();\n\t\tUppLog() << \"\\nHere is a matrix whose columns form a basis of the null-space of A:\\n\"\n\t\t << lu_decomp.kernel();\n\t\tUppLog() << \"\\nHere is a matrix whose columns form a basis of the column-space of A:\\n\"\n\t\t << lu_decomp.image(A); // yes, have to pass the original A\n\t}\n\t{\n\t\tMatrix2d A;\n\t\tA << 2, 1,\n\t\t 2, 0.9999999999;\n\t\tFullPivLU lu(A);\n\t\tUppLog() << \"\\nBy default, the rank of A is found to be \" << lu.rank();\n\t\tlu.setThreshold(1e-5);\n\t\tUppLog() << \"\\nWith threshold 1e-5, the rank of A is found to be \" << lu.rank();\n\t}\n\t\n\t// https://eigen.tuxfamily.org/dox/group__TutorialReductionsVisitorsBroadcasting.html\n\tUppLog() << \"\\n\\nTutorial page 7 - Reductions, visitors and broadcasting\";\n\t\t\n\tUppLog() << \"\\n\\nReductions\";\n\t{\n\t\tEigen::Matrix2d mat;\n\t\tmat << 1, 2,\n\t\t\t 3, 4;\n\t\tUppLog() << \"\\nHere is mat.sum(): \" << mat.sum();\n\t\tUppLog() << \"\\nHere is mat.prod(): \" << mat.prod();\n\t\tUppLog() << \"\\nHere is mat.mean(): \" << mat.mean();\n\t\tUppLog() << \"\\nHere is mat.minCoeff(): \" << mat.minCoeff();\n\t\tUppLog() << \"\\nHere is mat.maxCoeff(): \" << mat.maxCoeff();\n\t\tUppLog() << \"\\nHere is mat.trace(): \" << mat.trace();\n\t}\t\n\tUppLog() << \"\\n\\nNorm computations\";\n\t{\n\t\tVectorXf v(2);\n\t\tMatrixXf m(2,2), n(2,2);\n\t\t\n\t\tv << -1,\n\t\t \t 2;\n\t\t\n\t\tm << 1,-2,\n\t\t\t-3, 4;\n\t\t\n\t\tUppLog() << \"\\nv.squaredNorm() = \" << v.squaredNorm();\n\t\tUppLog() << \"\\nv.norm() = \" << v.norm();\n\t\tUppLog() << \"\\nv.lpNorm<1>() = \" << v.lpNorm<1>();\n\t\tUppLog() << \"\\nv.lpNorm() = \" << v.lpNorm();\n\t\t\n\t\tUppLog() << \"\\n\";\n\t\tUppLog() << \"\\nm.squaredNorm() = \" << m.squaredNorm();\n\t\tUppLog() << \"\\nm.norm() = \" << m.norm();\n\t\tUppLog() << \"\\nm.lpNorm<1>() = \" << m.lpNorm<1>();\n\t\tUppLog() << \"\\nm.lpNorm() = \" << m.lpNorm();\n\t}\n\tUppLog() << \"\\n\\nBoolean reductions\";\n\t{\n\t\tArrayXXf a(2,2);\n\t\t\n\t\ta << 1,2,\n\t\t \t 3,4;\n\t\t\n\t\tUppLog() << \"\\n(a > 0).all() = \" << (a > 0).all();\n\t\tUppLog() << \"\\n(a > 0).any() = \" << (a > 0).any();\n\t\tUppLog() << \"\\n(a > 0).count() = \" << (a > 0).count();\n\t\tUppLog() << \"\\n\";\n\t\tUppLog() << \"\\n(a > 2).all() = \" << (a > 2).all();\n\t\tUppLog() << \"\\n(a > 2).any() = \" << (a > 2).any();\n\t\tUppLog() << \"\\n(a > 2).count() = \" << (a > 2).count();\n\t}\n\tUppLog() << \"\\n\\nVisitors\";\n\t{\n\t\tEigen::MatrixXf m(2,2);\n\t\t\n\t\tm << 1, 2,\n\t\t \t 3, 4;\n\t\t\n\t\t//get location of maximum\n\t\tMatrixXf::Index maxRow, maxCol;\n\t\tfloat max = m.maxCoeff(&maxRow, &maxCol);\n\t\t\n\t\t//get location of minimum\n\t\tMatrixXf::Index minRow, minCol;\n\t\tfloat min = m.minCoeff(&minRow, &minCol);\n\t\t\n\t\tUppLog() << \"\\nMax: \" << max << \", at: \" << maxRow << \",\" << maxCol;\n\t\tUppLog() << \"\\nMin: \" << min << \", at: \" << minRow << \",\" << minCol;\n\t}\n\tUppLog() << \"\\n\\nPartial reductions\";\n\t{\n\t\tEigen::MatrixXf mat(2,4);\n\t\tmat << 1, 2, 6, 9,\n\t\t 3, 1, 7, 2;\n\t\t\n\t\tUppLog() << \"\\nColumn's maximum: \\n\" << mat.colwise().maxCoeff();\n\t}\n\t{\n\t\tEigen::MatrixXf mat(2,4);\n\t\tmat << 1, 2, 6, 9,\n\t\t 3, 1, 7, 2;\n\t\t\n\t\tUppLog() << \"\\nRow's maximum: \\n\" << mat.rowwise().maxCoeff();\n\t}\n\tUppLog() << \"\\n\\nCombining partial reductions with other operations\";\n\t{\n\t\tMatrixXf mat(2,4);\n\t\tmat << 1, 2, 6, 9,\n\t\t 3, 1, 7, 2;\n\t\t\n\t\tMatrixXf::Index maxIndex;\n\t\tfloat maxNorm = mat.colwise().sum().maxCoeff(&maxIndex);\n\t\t\n\t\tUppLog() << \"\\nMaximum sum at position \" << maxIndex;\n\t\t\n\t\tUppLog() << \"\\nThe corresponding vector is: \";\n\t\tUppLog() << \"\\n\" << mat.col( maxIndex );\n\t\tUppLog() << \"\\nAnd its sum is is: \" << maxNorm;\n\t}\n\tUppLog() << \"\\n\\nBroadcasting\";\n\t{\n\t\tEigen::MatrixXf mat(2,4);\n\t\tEigen::VectorXf v(2);\n\t\t\n\t\tmat << 1, 2, 6, 9,\n\t\t 3, 1, 7, 2;\n\t\t \n\t\tv << 0,\n\t\t 1;\n\t\t \n\t\t//add v to each column of m\n\t\tmat.colwise() += v;\n\t\t\n\t\tUppLog() << \"\\nBroadcasting result: \";\n\t\tUppLog() << \"\\n\" << mat;\n\t}\n\t{\n\t\tEigen::MatrixXf mat(2,4);\n\t\tEigen::VectorXf v(4);\n\t\t\n\t\tmat << 1, 2, 6, 9,\n\t\t 3, 1, 7, 2;\n\t\t \n\t\tv << 0,1,2,3;\n\t\t \n\t\t//add v to each row of m\n\t\tmat.rowwise() += v.transpose();\n\t\t\n\t\tUppLog() << \"\\nBroadcasting result: \";\n\t\tUppLog() << \"\\n\" << mat;\n\t}\n\tUppLog() << \"\\n\\nCombining broadcasting with other operations\";\n\t{\n\t\tEigen::MatrixXf m(2,4);\n\t\tEigen::VectorXf v(2);\n\t\t\n\t\tm << 1, 23, 6, 9,\n\t\t \t 3, 11, 7, 2;\n\t\t \n\t\tv << 2,\n\t\t 3;\n\t\t\n\t\tMatrixXf::Index index;\n\t\t// find nearest neighbour\n\t\t(m.colwise() - v).colwise().squaredNorm().minCoeff(&index);\n\t\t\n\t\tUppLog() << \"\\nNearest neighbour is column \" << index << \":\";\n\t\tUppLog() << \"\\n\" << m.col(index);\n\t}\n\t\t\n\tUppLog() << \"\\n\\nSerializing tests\";\n\t{\n\t\tSerialTest serialTest, serialTest_j, serialTest_x, serialTest_s;\n\t\tserialTest.m << 1, 2,\n\t\t \t\t\t4, 8;\n\t\tserialTest.v << 1, 2, 4;\n\n\t\tStoreAsJsonFile(serialTest, GetExeDirFile(\"Json.txt\"));\n\t\tLoadFromJsonFile(serialTest_j, GetExeDirFile(\"Json.txt\"));\n\t\tUppLog() << \"\\nJSON demo\";\n\t\tserialTest_j.Print();\n\t\t\n\t\tStoreAsXMLFile(serialTest, \"XMLdata\", GetExeDirFile(\"Xml.txt\"));\n\t\tLoadFromXMLFile(serialTest_x, GetExeDirFile(\"Xml.txt\"));\n\t\tUppLog() << \"\\nXML demo\";\n\t\tserialTest_x.Print();\n\t\t\n\t\tStoreToFile(serialTest, GetExeDirFile(\"Serial.dat\"));\n\t\tLoadFromFile(serialTest_s, GetExeDirFile(\"Serial.dat\"));\n\t\tUppLog() << \"\\nSerialization demo\";\n\t\tserialTest_s.Print();\n\t}\n\t\n\tNonLinearTests();\n\t\n\tFFTTests();\n\t\n\t#ifdef flagDEBUG\n\tCout() << \"\\nPress enter key to end\";\n\tReadStdIn();\n\t#endif \n}\n\n\n\n", "meta": {"hexsha": "6af7651135eeaae6aa20a9f22bd2d381ea23797d", "size": 20415, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/Eigen_demo_cl/eigen_demo.cpp", "max_stars_repo_name": "XOULID/Anboto", "max_stars_repo_head_hexsha": "2743b066f23bf2db9cc062d3adedfd044bc69ec1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Eigen_demo_cl/eigen_demo.cpp", "max_issues_repo_name": "XOULID/Anboto", "max_issues_repo_head_hexsha": "2743b066f23bf2db9cc062d3adedfd044bc69ec1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Eigen_demo_cl/eigen_demo.cpp", "max_forks_repo_name": "XOULID/Anboto", "max_forks_repo_head_hexsha": "2743b066f23bf2db9cc062d3adedfd044bc69ec1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6325385694, "max_line_length": 105, "alphanum_fraction": 0.5414156258, "num_tokens": 7972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.8479677660619634, "lm_q1q2_score": 0.7827074545520885}} {"text": "#include \"Euclidean.h\"\n\n#include \nusing namespace boost::multiprecision;\n\nEuclidean::Euclidean()\n{};\n\nEuclidean::~Euclidean()\n{};\n\nint256_t Euclidean::extendedEuclidean(int256_t a, int256_t b, int256_t* x, int256_t* s)\n{\n if ((a == 0) || (b == 0))\n {\n return 0;\n }\n\n int256_t q = 0;\n int256_t r = 0;\n\n q = a / b;\n\n //remainder\n r = a % b;\n\n int256_t x_tmp = *x;\n int256_t s_tmp = *s;\n if (r != 0)\n {\n extendedEuclidean(b, r, &x_tmp, &s_tmp);\n }\n\n if (r == 0)\n {\n *x = 0;\n *s = 1;\n\n return b;\n }\n\n *x = s_tmp;\n *s = x_tmp - (q * s_tmp);\n\n return b;\n}\n\nint256_t Euclidean::euclidean(int256_t a, int256_t b)\n{\n\n if ((a == 0) || (b == 0))\n {\n return 0;\n }\n\n int256_t q;\n int256_t r;\n\n do\n {\n q = a / b;\n r = a % b;\n\n a = b;\n b = r;\n } while (r != 0);\n\n return a;\n}", "meta": {"hexsha": "f68fda38f4c5f065fa0caa39780f8b20cca2ab36", "size": 852, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/Euclidean.cpp", "max_stars_repo_name": "weniseb/RSA_CPP", "max_stars_repo_head_hexsha": "ea819e30e133205e780df94c17dc5f9236ec9739", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-01-04T07:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:03:49.000Z", "max_issues_repo_path": "src/math/Euclidean.cpp", "max_issues_repo_name": "weniseb/RSA_CPP", "max_issues_repo_head_hexsha": "ea819e30e133205e780df94c17dc5f9236ec9739", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-01-10T13:03:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-22T19:12:02.000Z", "max_forks_repo_path": "src/math/Euclidean.cpp", "max_forks_repo_name": "weniseb/RSA_CPP", "max_forks_repo_head_hexsha": "ea819e30e133205e780df94c17dc5f9236ec9739", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-25T20:57:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T08:42:35.000Z", "avg_line_length": 12.347826087, "max_line_length": 87, "alphanum_fraction": 0.5187793427, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7826446849043569}} {"text": "#include \n#include \n\n#include \n#include \n\nclass MultiVariateNormal\n{\npublic:\n MultiVariateNormal(const Eigen::VectorXd mean, const Eigen::MatrixXd covariance)\n : mean_(mean), covariance_(covariance)\n {\n Eigen::SelfAdjointEigenSolver eigen_solver(covariance_);\n transform_ = eigen_solver.eigenvectors() * eigen_solver.eigenvalues().cwiseSqrt().asDiagonal();\n }\n double pdf(const Eigen::VectorXd & x) const\n {\n double n = x.rows();\n double a = (x - mean_).transpose() * covariance_.inverse() * (x - mean_);\n double b = std::pow(std::sqrt(2 * M_PI), n) * std::sqrt(covariance_.determinant());\n return std::exp(-0.5 * a) / b;\n }\n\n Eigen::VectorXd operator()() const\n {\n static std::random_device seed;\n static std::mt19937 engine(seed());\n static std::normal_distribution<> dist;\n\n return mean_ + transform_ * Eigen::VectorXd{mean_.size()}.unaryExpr([&](auto x) { return dist(engine); });\n }\n void setMean(const Eigen::VectorXd mean) { mean_ = mean; }\n void setCovariance(const Eigen::MatrixXd covariance) { covariance_ = covariance; }\n\nprivate:\n Eigen::VectorXd mean_;\n Eigen::MatrixXd covariance_;\n Eigen::MatrixXd transform_;\n};\n\nint main(int argc, char ** argv)\n{\n Eigen::VectorXd mean(2);\n Eigen::MatrixXd covariance(2, 2);\n\n mean << 0.0, 0.0;\n covariance << 1.0, 0.1, 0.1, 1.0;\n\n MultiVariateNormal multi_variate_normal(mean, covariance);\n\n Eigen::VectorXd x(2);\n x << 0.2, 0.3;\n std::cout << multi_variate_normal.pdf(x) << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "a7d8b31331661f428f7c103d43e487fb115ac94b", "size": 1571, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/distribution/multi_variate_generator.cpp", "max_stars_repo_name": "RyuYamamoto/sandbox", "max_stars_repo_head_hexsha": "799f32f92eea944c8d467cccd24f8bd4cd80a9d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++/distribution/multi_variate_generator.cpp", "max_issues_repo_name": "RyuYamamoto/sandbox", "max_issues_repo_head_hexsha": "799f32f92eea944c8d467cccd24f8bd4cd80a9d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c++/distribution/multi_variate_generator.cpp", "max_forks_repo_name": "RyuYamamoto/sandbox", "max_forks_repo_head_hexsha": "799f32f92eea944c8d467cccd24f8bd4cd80a9d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5614035088, "max_line_length": 110, "alphanum_fraction": 0.6785486951, "num_tokens": 447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.962673111584966, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.7825255036222186}} {"text": "// Tester.cpp : Defines the entry point for the console application.\n//\n\n#include \n#include \n#include \"Chapter3.h\"\n\nint DemoConsoleOutput();\nint MatrixMultiplication();\nint TransposeProperties();\nint MultiplyingTransposedVectors();\nint MatrixTransposedVectorMultiplication();\nint InnerProduct();\n\nint main()\n{\n\tstd::cout << \"Linear Algebra: Concepts and Methods with Eigen\" << std::endl;\n\t//MatrixMultiplication();\n\t//TransposeProperties();\n\t//MultiplyingTransposedVectors();\n\t//MatrixTransposedVectorMultiplication();\n\t//InnerProduct();\n\tChapter3 chapter3;\n\tchapter3.IntroduceSelf();\n\treturn 0;\n}\n\nint MatrixMultiplication()\n{\n\tstd::cout << \"1.10: Matrix Multiplication\" << std::endl;\n\tEigen::MatrixXd matrix1(4, 3);\n\tmatrix1(0, 0) = 1;\n\tmatrix1(1, 0) = 2;\n\tmatrix1(2, 0) = 1;\n\tmatrix1(3, 0) = 2;\n\n\tmatrix1(0, 1) = 1;\n\tmatrix1(1, 1) = 0;\n\tmatrix1(2, 1) = 2;\n\tmatrix1(3, 1) = 2;\n\n\tmatrix1(0, 2) = 1;\n\tmatrix1(1, 2) = 1;\n\tmatrix1(2, 2) = 4;\n\tmatrix1(3, 2) = -1;\n\n\tstd::cout << \"Matrix 1:\" << std::endl;\n\tstd::cout << matrix1 << std::endl;\n\n\tEigen::MatrixXd matrix2(3, 2);\n\tmatrix2(0, 0) = 3;\n\tmatrix2(1, 0) = 1;\n\tmatrix2(2, 0) = -1;\n\n\tmatrix2(0, 1) = 0;\n\tmatrix2(1, 1) = 1;\n\tmatrix2(2, 1) = 3;\n\n\tstd::cout << \"Matrix 2:\" << std::endl;\n\tstd::cout << matrix2 << std::endl;\n\n\tstd::cout << \"Matrix 1 * Matrix 2:\" << std::endl;\n\tstd::cout << matrix1 * matrix2 << std::endl;\n\n\treturn 0;\n}\n\nint TransposeProperties()\n{\n\tstd::cout << \"1.29: Transpose Properties\" << std::endl;\n\n\tEigen::Matrix2f matrix1;\n\tmatrix1 << 1, 2, 6, 8;\n\tEigen::Matrix2f matrix2;\n\tmatrix2 << 3, 4, 10, 12;\n\tstd::cout << \"matrix1*matrix2 transpose\" << std::endl;\n\tstd::cout << (matrix1 * matrix2).transpose() << std::endl;\n\tstd::cout << \"should equal matrix2 transpose *matrix1 transpose\" << std::endl;\n\tstd::cout << matrix2.transpose() * matrix1.transpose() << std::endl;\n\tstd::cout << \"and should not equal matrix1 transpose * matrix2 transpose\" << std::endl;\n\tstd::cout << matrix1.transpose() * matrix2.transpose() << std::endl;\n\n\treturn 0;\n}\n\nint MultiplyingTransposedVectors()\n{\n\tstd::cout << \"1.33: Calculate aTb and abT\" << std::endl;\n\n\tEigen::Vector3d vectorA(1,2,3);\n\tEigen::Vector3d vectorB(4, -2, 1);\n\tstd::cout << \"a transpose\" << std::endl;\n\tstd::cout << vectorA.transpose() << std::endl;\n\tstd::cout << \"times b\" << std::endl;\n\tstd::cout << vectorA.transpose() * vectorB<< std::endl;\n\tstd::cout << \"and b transpose * a\" << std::endl;\n\tstd::cout << vectorA * vectorB.transpose() << std::endl;\n\n\treturn 0;\n}\n\nint MatrixTransposedVectorMultiplication()\n{\n\tstd::cout << \"1.38: Vectors and matrices\" << std::endl;\n\n\tEigen::Vector3d vectorA(1, 2, 3);\n\tEigen::Matrix3d matrixA;\n\tmatrixA << 1, 1, 1, \n\t\t2, 2, 2, \n\t\t3, 3, 3;\n\tstd::cout << \"a transpose\" << std::endl;\n\tstd::cout << vectorA.transpose() << std::endl;\n\tstd::cout << \"times matrixA\" << std::endl;\n\tstd::cout << matrixA << std::endl;\n\tstd::cout << \"equals\" << std::endl;\n\tstd::cout << vectorA.transpose() * matrixA << std::endl;\n\n\treturn 0;\n}\n\nint InnerProduct()\n{\n\tstd::cout << \"1.92: Inner Product\" << std::endl;\n\n\tEigen::Vector2d a(1, 2);\n\tEigen::Vector2d b(3, 1);\n\tauto t = a.transpose().dot(b.transpose());\n\tauto l_of_a = sqrt(a.transpose().dot(a.transpose()));\n\tauto l_of_b = sqrt(b.transpose().dot(b.transpose()));\n\tauto lp = l_of_a * l_of_b;\n\tauto ct = t / lp;\n\n\tstd::cout << \"law of cosines states the inner product off the transposes of (1,2) and (3,1) \" << std::endl;\n\tstd::cout << t << std::endl;\n\tstd::cout << \"divided by the product of the lengths of said matrices\" << std::endl;\n\tstd::cout << lp << std::endl;\n\tstd::cout << ct << std::endl;\n\tstd::cout << \"is equal to the product of the square root of the inner product of each of said matrixes with themselves times cosine theta\" << std::endl;\n\tstd::cout << lp * ct << std::endl;\n\n\treturn 0;\n}\n\nint DemoConsoleOutput()\n{\n\tEigen::MatrixXd matrix1(2, 2);\n\tmatrix1(0, 0) = 3;\n\tmatrix1(1, 0) = 2.5;\n\tmatrix1(0, 1) = -1;\n\tmatrix1(1, 1) = matrix1(1, 0) + matrix1(0, 1);\n\tstd::cout << matrix1 << std::endl;\n\n\tstd::cout << \"This is a simple string literal\" << std::endl;\n\n\tstd::cout << \"Pi when approximated is 22 / 7 = \" << 22 / 7 << std::endl;\n\n\tstd::cout << \"Pi actually is 22 / 7 = \" << 22.0 / 7 << std::endl;\n\n\treturn 0;\t\n}\n", "meta": {"hexsha": "ccdda5a63be358b512699cbd0eaacc01b3b7c66c", "size": 4239, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tester/WholeBook.cpp", "max_stars_repo_name": "MarshHawkEbsco/LinearAlgebraConceptsAndMethods", "max_stars_repo_head_hexsha": "f9486058b883ff7c100691469769424a2d2c8824", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tester/WholeBook.cpp", "max_issues_repo_name": "MarshHawkEbsco/LinearAlgebraConceptsAndMethods", "max_issues_repo_head_hexsha": "f9486058b883ff7c100691469769424a2d2c8824", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tester/WholeBook.cpp", "max_forks_repo_name": "MarshHawkEbsco/LinearAlgebraConceptsAndMethods", "max_forks_repo_head_hexsha": "f9486058b883ff7c100691469769424a2d2c8824", "max_forks_repo_licenses": ["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.3291925466, "max_line_length": 153, "alphanum_fraction": 0.6308091531, "num_tokens": 1418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476943, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7820188003467349}} {"text": "#pragma once\n\n// Include Eigen\n#include \n#include \n#ifdef USE_SPARSE_EIGEN\n#include \ntypedef Eigen::SparseMatrix MatrixType;\n#else\ntypedef Eigen::MatrixXf MatrixType;\n#endif\n\n// Include STL\n#include \n#include \n\n// Local include\n#include \"AxialMoments.hpp\"\n\n/* _Zonal Weigths_\n *\n * Compute the matrix of weights w_{l,i} that converts dot powers (wd, w)^i\n * to a Zonal Hamonics. More precisely:\n *\n * y_{l, 0}(w · wd) = ∑_i w_{l,i} (w · wd)^i, V l in [0 .. order]\n *\n */\ninline Eigen::MatrixXf ZonalWeights(int order) {\n\n // W is the matrix of the weights. It is build recursively using the Legendre\n // polynomials. The trick here is that Legendre polynomials are simply the\n // shift in order of a previous pol. summed to another previous pol.\n Eigen::MatrixXf W = Eigen::MatrixXf::Zero(order, order);\n W(0,0) = 1.0f;\n W(1,1) = 1.0f;\n for(int n=2; n\ninline Eigen::MatrixXf ZonalWeights(const std::vector& directions) {\n\n const int dsize = directions.size();\n const int order = (dsize-1) / 2 + 1;\n const int mrows = order*order;\n\n Eigen::MatrixXf result = Eigen::MatrixXf::Zero(mrows, dsize*order);\n\n const auto ZW = ZonalWeights(order);\n\n // Each vector fills a given set of column entries with decreasing\n // number to do the swapping. For example, the 0th vector will fill\n // entries from order 0 to max_order but the 1srt vector will fill\n // entries from 1 to max_order.\n for(int i=0; i= 2*j+1) {\n continue;\n }\n\n const int shift_rows = j*j + i;\n const int shift_cols = order*i;\n\n result.block(shift_rows, shift_cols, 1, order) = ZW.row(j);\n }\n }\n return result;\n}\n\n/* _Zonal Normalization_\n *\n * This little code compute the zonal normalization for spherical harmonics\n * basis using the √(2l+1 / 4π) factor. It can later by applied to a zonal\n * vector using Eigen fast product: a.cwiseProduct(b)\n */\ninline Eigen::VectorXf ZonalNormalization(int order) {\n Eigen::VectorXf res = Eigen::VectorXf(order);\n const float f = 1.0f/sqrt(4.0f*M_PI);\n for(int i=0; i\ninline Eigen::VectorXf RotatedZH(const Vector& d, const Vector& w, int order) {\n\n Eigen::VectorXf res = Eigen::VectorXf::Zero(order);\n const float z = Vector::Dot(d, w);\n\n res[0] = 1.0f;\n if(order == 1) {\n return res /sqrt(4.0f*M_PI);\n }\n\n res[1] = z;\n if(order == 2) {\n res[1] *= sqrt(3.0f);\n return res / sqrt(4.0f*M_PI);\n }\n\n // Using Bonnet recurrence formula\n for(int i=2; i\ninline Eigen::VectorXf ZHEvalFast(const std::vector& dirs, const Vector& w) {\n\n // Get the number of elements to compute\n const int dsize = dirs.size();\n const int order = (dsize-1) / 2 + 1;\n const int vsize = order*order;\n\n Eigen::VectorXf v(vsize);\n\n // The loop is first over the order term then over the set of directions\n // starting from the 0 index that is reused for all bands.\n float ylm = 0.0;\n for(int i=0; i(n, w, order);\n\n for(int l=0; l= 2*l+1) {\n continue;\n }\n v[l*l + i] = ylm[l];\n }\n }\n\n return v;\n}\n\n\n/* _Zonal Expansion_\n *\n * Expands a Spherical Harmonics vector into a Zonal Harmonics matrix transform.\n * Each band of spherical harmonics is decomposed into a set of Zonal Hamonics\n * with specific directions `directions`.\n *\n * The conversion matrix A is computed as the inverse of the evaluation of the\n * SH basis a the particular directions.\n *\n * The vector of directions must be of size `2*order+1`, where `order` is the\n * max order of the SH expansion.\n *\n * The template class SH must permit to access its basis elements, the y_{l,m}\n * as the static function `SH::FastBasis(const Vector& w, int order)`.\n */\ntemplate\ninline MatrixType ZonalExpansion(const std::vector& directions) {\n\n // Get the current band. Here I use a shifted order number. The integer\n // order is actually `order+1` to compute the number of rows and iterate\n // over it. Later in the code I evaluate the correct order to get the\n // ylm from SH::FastBasis.\n const int dsize = directions.size();\n const int order = (dsize-1) / 2 + 1;\n const int mrows = order*order;\n assert(order >= 0);\n\n const auto zhNorm = ZonalNormalization(order);\n\n#ifdef USE_SPARSE_EIGEN\n MatrixType Y(mrows, mrows);\n std::vector> triplets;\n#else\n MatrixType Y = Eigen::MatrixXf::Zero(mrows, mrows);\n#endif\n for(int i=0; i= 2*j+1) {\n continue;\n }\n\n const int shift = j*j;\n const int vsize = 2*j+1;\n#ifdef USE_SPARSE_EIGEN\n for(int k=0; k(shift+i, shift+k, v));\n }\n Y.setFromTriplets(triplets.begin(), triplets.end());\n#else\n Y.block(shift+i, shift, 1, vsize) = ylm.segment(shift, vsize).transpose() / zhNorm[j];\n#endif\n }\n }\n\n return Y;\n}\n\n/* _Compute the Inverse of Matrix Y_\n *\n * Since the matrix resulting from ZonalExpansion is block diagonal, its\n * inverse is trivial to compute. We must simply take the inverse of each\n * block, in place.\n *\n * TODO: Make the sparse version.\n */\ninline MatrixType computeInverse(const MatrixType& Y) {\n const int nrows = Y.rows();\n const int order = sqrt(nrows);\n\n#ifdef USE_SPARSE_EIGEN\n MatrixType A(mrows, nrows);\n std::vector> triplets;\n#else\n MatrixType A = Eigen::MatrixXf::Zero(nrows, nrows);\n#endif\n\n for(int j=0; j\ninline float computeSHIntegral(const Eigen::VectorXf& clm,\n const std::vector& basis,\n const Triangle& triangle) {\n\n // Get the Zonal weights matrix and the Zlm -> Ylm conversion matrix\n // and compute the product of the two: `Prod = A x Zw`.\n const auto ZW = ZonalWeights(basis);\n const auto Y = ZonalExpansion(basis);\n const auto A = computeInverse(Y);\n\n const auto Prod = A*ZW;\n\n // Analytical evaluation of the integral of power of cosines for\n // the different basis elements up to the order defined by the\n // number of elements in the basis\n const auto moments = AxialMoments(triangle, basis);\n\n return clm.dot(Prod * moments);\n}\n\n\n#ifdef LATER\n/* _Compute the SH Integral over a Spherial Triangle_\n *\n * This function is provided as an example of how to use the different\n * components of this package. It is probably much faster to precompute the\n * product `Prod` of the ZonalWeights and the Zonal to SH conversion matrix.\n */\ntemplate\ninline float computeSHIntegral(const Eigen::VectorXf& clm,\n const Triangle& triangle) {\n\n // Get the order of the provided SH vector and compute the directional\n // sampling of the sphere for rotated ZH/cosines.\n const auto order = sqrt(clm.size())-1;\n const auto basis = SamplingFibonacci(2*order+1);\n\n // Get the Zonal weights matrix and the Zlm -> Ylm conversion matrix\n // and compute the product of the two: `Prod = A x Zw`.\n const auto ZW = ZonalWeights(basis);\n const auto Y = ZonalExpansion(basis);\n const auto A = computeInverse(Y);\n\n const auto Prod = A*ZW;\n\n // Analytical evaluation of the integral of power of cosines for\n // the different basis elements up to the order defined by the\n // number of elements in the basis\n const auto moments = AxialMoments(triangle, basis);\n\n return clm.dot(Prod * moments);\n}\n#endif\n", "meta": {"hexsha": "aa1a7a7d2c18deea9fb866728a5d2327c837ed3f", "size": 10471, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/SphericalIntegration.hpp", "max_stars_repo_name": "belcour/IntegralSH", "max_stars_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 48.0, "max_stars_repo_stars_event_min_datetime": "2018-02-27T07:07:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T04:40:06.000Z", "max_issues_repo_path": "include/SphericalIntegration.hpp", "max_issues_repo_name": "belcour/IntegralSH", "max_issues_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/SphericalIntegration.hpp", "max_forks_repo_name": "belcour/IntegralSH", "max_forks_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-05-08T09:28:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-01T03:40:39.000Z", "avg_line_length": 30.2630057803, "max_line_length": 95, "alphanum_fraction": 0.6436825518, "num_tokens": 2973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422213778251, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7820187897812665}} {"text": "//\n// Created by James Koh on 03/02/2021.\n//\n\n#include \n#include \n\nnamespace DM {\n using namespace Eigen;\n\n MatrixXd Direction(VectorXd jacobian, MatrixXd hessian_inverse) {\n return - hessian_inverse * jacobian;\n }\n\n double LambdaSquared(VectorXd jacobian, MatrixXd hessian_inverse) {\n return jacobian.transpose() * hessian_inverse * jacobian;\n }\n\n VectorXd LineSearchUpdate(VectorXd x, VectorXd delta_x, double alpha, double beta,\n double F (VectorXd), VectorXd jacobian) {\n double t = 1.0;\n\n while (F(x + t * delta_x) > (F(x) + jacobian.dot(delta_x) * (alpha * t))) {\n t = beta * t;\n }\n\n return x + t * delta_x;\n }\n\n VectorXd Newton(VectorXd x0, double epsilon, double alpha, double beta,\n double F (VectorXd), VectorXd J (VectorXd), MatrixXd H (VectorXd)) {\n VectorXd x = x0;\n int i = 1;\n\n while (true) {\n std::cout << \"Iteration \" << i << \":\" << std::endl;\n\n VectorXd jacobian = J(x);\n MatrixXd hessian = H(x);\n MatrixXd hessian_inverse = H(x).inverse();\n\n VectorXd delta_x = Direction(jacobian, hessian_inverse);\n double lambda_squared = LambdaSquared(jacobian, hessian_inverse);\n\n std::cout << \"Lambda^2: \" << lambda_squared << std::endl;\n\n if (lambda_squared / 2 < epsilon || i > 100)\n break;\n\n x = LineSearchUpdate(x, delta_x, alpha, beta, F, jacobian);\n std::cout << \"Solution :\" << F(x) << std::endl;\n\n i++;\n }\n\n return x;\n }\n}", "meta": {"hexsha": "eea69f81376b52478f0e4800fc52d2692ea15ca6", "size": 1659, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "descentmethods.cpp", "max_stars_repo_name": "jameshskoh/DescentMethods-CPP", "max_stars_repo_head_hexsha": "0e0ad532b8de01a8d511489b97ddde6b234e7e48", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "descentmethods.cpp", "max_issues_repo_name": "jameshskoh/DescentMethods-CPP", "max_issues_repo_head_hexsha": "0e0ad532b8de01a8d511489b97ddde6b234e7e48", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "descentmethods.cpp", "max_forks_repo_name": "jameshskoh/DescentMethods-CPP", "max_forks_repo_head_hexsha": "0e0ad532b8de01a8d511489b97ddde6b234e7e48", "max_forks_repo_licenses": ["BSD-3-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.6034482759, "max_line_length": 88, "alphanum_fraction": 0.5533453888, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.7819308656996085}} {"text": "#include \"writer.hpp\"\n#include \n#include \n#include \n#include \n#include \n\n//! Sparse Matrix type. Makes using this type easier.\ntypedef Eigen::SparseMatrix SparseMatrix;\n\n//! Used for filling the sparse matrix.\ntypedef Eigen::Triplet Triplet;\n\n//! Vector type\ntypedef Eigen::VectorXd Vector;\n\n//! Our function pointer, typedef'd to make it easier to use\ntypedef double (*FunctionPointer)(double);\n\n//! Create the Stiffness matrix for 1D with boundary terms\n//! @param[out] A will be the Galerkin matrix (as in the exercise)\n//! @param[in] N as in the exercise\n//! @param[in] dx the cell length\nvoid createStiffnessMatrixWithBoundary(SparseMatrix &A, int N, double dx) {\n\tstd::vector triplets;\n\tA.resize(N + 2, N + 2);\n\n\t// Reserve the space we will allocate\n\ttriplets.reserve((N + 2) + 2 * N + 2);\n\n\t// (write your solution here)\n\tA.setZero();\n\tfor (int i = 0; i < N + 2; i++) {\n\t\ttriplets.push_back(Triplet(i, i, 2 / dx));\n\t\tif (i >= 1) {\n\t\t\ttriplets.push_back(Triplet(i, i - 1, -1 / dx));\n\t\t}\n\t\tif (i <= N + 1) {\n\t\t\ttriplets.push_back(Triplet(i, i + 1, -1 / dx));\n\t\t}\n\t}\n\tA.setFromTriplets(triplets.begin(), triplets.end());\n}\n\n//! Creates the right hand side for the finite element method in the exericse\n//! @param[out] rhs the resulting right hand side (or phi in the exercise)\n//! @param[in] f the function pointer to f\n//! @param[in] dx the cell length\n//! @param[in] x the x points\nvoid createRHS(Vector &rhs, FunctionPointer f, int N, double dx, const Vector &x) {\n\trhs.resize(N + 2);\n\n\t// (write your solution here)\n\trhs(0) = dx / 2 * f(x(0));\n\tfor (int i = 1; i < N + 1; i++) {\n\t\trhs(i) = dx * f(x(i));\n\t}\n\trhs(N + 1) = dx / 2 * f(x(N + 1));\n}\n\n//! Solve the equation\n//!\n//! $-u''(x) = f(x)$\n//!\n//! using FEM on the interval $[a,b]$.\n//!\n//! @param[out] u at the end, will have all the values of u\n//! @param[out] x will be the x points\n//! @param[in] f should be a pointer to the function f\n//! @param[in] N number of inner cells to use\n//! @param[in] a endpoint on left side\n//! @param[in] b endpoint on right side\n//! @param[in] ua boundary value at a\n//! @param[in] ub boundary value at b\nvoid femSolve(Vector &u, Vector &x, FunctionPointer f, int N, double a, double b, double ua = 0.0, double ub = 0.0) {\n\tdouble dx = (b - a) / (N + 1);\n\n\t// Fill x vector\n\tx.setLinSpaced(N + 2, a, b);\n\n\tSparseMatrix A;\n\tcreateStiffnessMatrixWithBoundary(A, N, dx);\n\n\tVector phi;\n\tcreateRHS(phi, f, N, dx, x);\n\n\t// (write your solution here)\n\n\tu.resize((N + 2));\n\tu.setZero();\n\n\t// Do boundary conditions\n\t// (write your solution here)\n\tu(0) = ua;\n\tu(N + 1) = ub;\n\tphi -= A * u;\n\n\t//solve inner system\n\t// (write your solution here)\n\tSparseMatrix innerA = A.block(1, 1, N, N);\n\n\tEigen::SparseLU solver;\n\tsolver.compute(innerA);\n\tif (solver.info() != Eigen::Success) {\n\t\tthrow std::runtime_error(\"Could not decompose the matrix.\");\n\t}\n\tu.segment(1, N) = solver.solve(phi.segment(1, N));\n}\n\nvoid computeWithoutBoundaryValues() {\n\tVector u;\n\tVector x;\n\tfemSolve(u, x, std::sin, 100, -M_PI, M_PI);\n\n\twriteToFile(\"u_wo_bc_fem.txt\", u);\n\twriteToFile(\"x_wo_bc_fem.txt\", x);\n}\n\nvoid computeWithBoundaryValues() {\n\tVector u;\n\tVector x;\n\tfemSolve(u, x, std::cos, 100, -M_PI, M_PI, -1.0, 1.0 / 2.0);\n\n\twriteToFile(\"u_w_bc_fem.txt\", u);\n\twriteToFile(\"x_w_bc_fem.txt\", x);\n}\n\nint main(int, char **) {\n\tcomputeWithoutBoundaryValues();\n\tcomputeWithBoundaryValues();\n}\n", "meta": {"hexsha": "65f749dbd7526e1626d94a11cf7258c441f2b3db", "size": 3465, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series2/1d-linFEM/fem.cpp", "max_stars_repo_name": "westernmagic/NumPDE", "max_stars_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "series2/1d-linFEM/fem.cpp", "max_issues_repo_name": "westernmagic/NumPDE", "max_issues_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-04-01T22:52:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T16:21:55.000Z", "max_forks_repo_path": "series2/1d-linFEM/fem.cpp", "max_forks_repo_name": "westernmagic/NumPDE", "max_forks_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.25, "max_line_length": 117, "alphanum_fraction": 0.6496392496, "num_tokens": 1093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979619, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7815583444442028}} {"text": "#include \n#include \n\n#include // Eigen 核心部分\n#include // 稠密矩阵的代数运算(逆,特征值等)\n#include // Eigen/Geometry 模块提供了各种旋转和平移的表示\n\n#include \n\nint main(int argc, char **argv){\n\n double a_e = 2.0, b_e = -1.0, c_e = 5.0; // 待拟合参数 及估计初值\n double a = 1.0, b = 2.0, c = 1.0; // 待拟合参数 实际值\n cv::RNG rng; // OpenCV 随机数产生器\n double w_sigma = 1.0;\n double inv_sigma = 1.0 / w_sigma;\n\n // 生成数据\n int num_data = 100;\n std::vector t_data, y_data;\n \n for(int i = 0; i < num_data; i++){\n double t = i / 100.0;\n double y = exp(a*t*t + b*t + c) + rng.gaussian(w_sigma * w_sigma);\n t_data.push_back(t);\n y_data.push_back(y);\n }\n\n std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now();\n // 迭代-优化\n Eigen::Vector3d x(a_e, b_e, c_e);\n int num_iters = 20;\n double cost = 0, lastCost = 0;\n \n for(int iter = 0; iter < num_iters; iter++){\n Eigen::Matrix3d H = Eigen::Matrix3d::Zero();\n Eigen::Vector3d g = Eigen::Vector3d::Zero();\n cost = 0;\n for (int i = 0; i < num_data; i++){\n double t = t_data[i];\n double y = y_data[i];\n double y_e = exp(x[0]*t*t + x[1]*t + x[2]);\n\n double error = y_e - y;\n Eigen::Matrix J;\n J[0] = t * t * exp(x[0]*t*t + x[1]*t + x[2]); \n J[1] = t * exp(x[0]*t*t + x[1]*t + x[2]);\n J[2] = exp(x[0]*t*t + x[1]*t + x[2]);\n\n H += inv_sigma * inv_sigma * J.transpose() * J;\n g += - inv_sigma * inv_sigma * J * error;\n cost += error * error;\n }\n\n if (iter >= 1 && cost >= lastCost){\n std::cout << \"cost >= lastCost, break.\" << std::endl; \n break;\n }\n lastCost = cost;\n\n Eigen::Vector3d dx = H.ldlt().solve(g);\n if (dx.norm() < 1e-6){\n std::cout << \"||dx|| < 1e-6, break.\" << std::endl;\n break;\n }\n x += dx;\n\n std::cout << \"iter = \" << iter << \" , estimated parameters = \" << x.transpose() \n << \" , cost = \" << cost << std::endl;\n }\n \n std::chrono::steady_clock::time_point t2 = std::chrono::steady_clock::now();\n std::chrono::duration time_used = std::chrono::duration_cast > (t2 - t1);\n \n std::cout << \"final , estimated parameters = \" << x.transpose() \n << \" , cost = \" << cost << std::endl;\n std::cout << \"time_cost = \" << time_used.count() << \"second\" << std::endl; \n\n\n return 0;\n}\n", "meta": {"hexsha": "8968bff8f9568a6d793d68ab635a2a4a224fc152", "size": 2628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "my_implementation_2/ch6/gaussNewton/gaussNewton.cpp", "max_stars_repo_name": "Mingrui-Yu/slambook2", "max_stars_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-09T14:18:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-09T14:18:15.000Z", "max_issues_repo_path": "my_implementation_2/ch6/gaussNewton/gaussNewton.cpp", "max_issues_repo_name": "Mingrui-Yu/slambook2", "max_issues_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "my_implementation_2/ch6/gaussNewton/gaussNewton.cpp", "max_forks_repo_name": "Mingrui-Yu/slambook2", "max_forks_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0487804878, "max_line_length": 115, "alphanum_fraction": 0.49695586, "num_tokens": 893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.8354835371034369, "lm_q1q2_score": 0.7814666119655032}} {"text": "\n/**\n * Reference: The code is copied from:\n * https://eigen.tuXdamily.org/dox/classEigen_1_1JacobiSVD.html\n */\n\n#include \n#include \n// #include // For initializing MatrixXd\n#include \n\nusing namespace std;\n\nint main(int argc, char const *argv[])\n{\n // Eigen::MatrixXd mat = Eigen::MatrixXd::Random(3, 2);\n // Eigen::MatrixXd mat = Eigen::MatrixXd::Zero(3, 2);\n // Eigen::Matrix3d mat = Eigen::Matrix3d::Zero();\n Eigen::MatrixXd mat(2, 2);\n mat(0, 0) = 1.0;\n mat(1, 0) = 1.0;\n mat(0, 1) = 5.0;\n mat(1, 1) = 5.0;\n\n cout << \"Here is the matrix mat:\" << endl\n << mat << endl;\n\n Eigen::JacobiSVD svd(mat, Eigen::ComputeThinU | Eigen::ComputeThinV);\n Eigen::Vector2d s = svd.singularValues();\n Eigen::Matrix u = svd.matrixU();\n Eigen::Matrix v = svd.matrixV();\n cout << \"Its singular values are:\" << endl\n << svd.singularValues() << endl;\n cout << \"Its left singular vectors are the columns of the thin U matrix:\" << endl\n << svd.matrixU() << endl;\n cout << \"Its right singular vectors are the columns of the thin V matrix:\" << endl\n << svd.matrixV() << endl;\n\n // Eigen::Vector3d rhs(1, 0, 0);\n Eigen::Vector2d rhs(1, 0);\n cout << \"Now consider this rhs vector:\" << endl\n << rhs << endl;\n cout << \"A least-squares solution of mat*x = rhs is:\" << endl\n << svd.solve(rhs) << endl;\n\n Eigen::Vector2d mean = mat.colwise().mean(); // 1, 5\n Eigen::Vector2d mean_row = mat.rowwise().mean(); // 3, 3\n typedef Eigen::Matrix Mat12d;\n Mat12d mean_col = mat.colwise().mean(); // 1, 5\n\n cout << \"Column wise mean: \" << mean << endl;\n cout << \"Row wise mean: \" << mean_row << endl;\n cout << \"Subtraction by colwise(): \" << mat.colwise() - mean << endl;\n cout << \"Subtraction by rowwise(): \" << mat.rowwise() - mean.transpose() << endl;\n\n Eigen::Vector2d first_column = mat.col(0);\n cout << \"\\n first_column: \" << first_column << endl;\n double norm_of_first_column = first_column.dot(first_column);\n cout << \"\\n norm_of_first_column: \" << norm_of_first_column << endl;\n \n return 0;\n}\n", "meta": {"hexsha": "a53040a45a7eef1493349939ee2c6cfe19c8d5da", "size": 2269, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/others/test_svd.cpp", "max_stars_repo_name": "felixchenfy/cpp_practice_image_processing", "max_stars_repo_head_hexsha": "72724097e3d9d35eb813fc04aac56d79419d6c7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-12-23T09:44:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-07T05:20:24.000Z", "max_issues_repo_path": "tests/others/test_svd.cpp", "max_issues_repo_name": "felixchenfy/cpp_practice_image_processing", "max_issues_repo_head_hexsha": "72724097e3d9d35eb813fc04aac56d79419d6c7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/others/test_svd.cpp", "max_forks_repo_name": "felixchenfy/cpp_practice_image_processing", "max_forks_repo_head_hexsha": "72724097e3d9d35eb813fc04aac56d79419d6c7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-01T02:11:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-18T12:48:06.000Z", "avg_line_length": 36.0158730159, "max_line_length": 91, "alphanum_fraction": 0.5888056413, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8872045981907006, "lm_q1q2_score": 0.7814472176549104}} {"text": "#include \n#include \n#include \n#include \n#include \n\n#include \"errors.hpp\"\n\nusing namespace Eigen;\n\nint main() {\n \n // Construct data for RK order 4\n MatrixXd A = MatrixXd::Zero(4,4);\n A(1,0) = .5;\n A(2,1) = .5;\n A(3,2) = 1;\n VectorXd b(4);\n b << 1./6, 1./3, 1./3, 1./6;\n \n // Construct data for the IVP\n double T = 1;\n int n = 5;\n VectorXd y0(2*n);\n for(int i = 0; i < n; ++i) {\n y0(i)=(i+1.)/n;\n y0(i+n)=-1;\n }\n\n auto f = [n] (VectorXd y) {\n VectorXd fy(2*n);\n \n VectorXd g(n);\n g(0) = y(0)*(y(1)+y(0));\n g(n-1) = y(n-1)*(y(n-1)+y(n-2));\n for(int i = 1; i < n-1; ++i) {\n g(i) = y(i)*(y(i-1)+y(i+1));\n }\n \n Eigen::SparseMatrix C(n,n);\n C.reserve(3);\n for(int i = 0; i < n; ++i) {\n C.insert(i,i) = 2;\n if(i < n-1) C.insert(i,i+1) = -1;\n if(i >= 1) C.insert(i,i-1) = -1;\n }\n C.makeCompressed();\n fy.head(n) = y.head(n);\n \n Eigen::SparseLU< Eigen::SparseMatrix > solver;\n solver.analyzePattern(C);\n solver.compute(C);\n fy.tail(n) = solver.solve(g);\n return fy;\n };\n\n errors(f, T, y0, A, b);\n}", "meta": {"hexsha": "17c1d518a20424537d7bf68ef1a7015d1056c98f", "size": 1318, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS12/solutions_ps12/system.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS12/solutions_ps12/system.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS12/solutions_ps12/system.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.724137931, "max_line_length": 63, "alphanum_fraction": 0.4408194234, "num_tokens": 464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.963779946215714, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.781123319007254}} {"text": "#include \n#include \n#include \nusing namespace Eigen;\n\nvoid func1(void) {\n MatrixXd A = MatrixXd::Random(5, 8);\n VectorXd b = VectorXd::Random(5);\n VectorXd b0 = b; //save b because we are going to write over during computations // You should have already done something like this.\n ColPivHouseholderQR qr(A.transpose());\n MatrixXd Q = qr.matrixQ(); // This computes A^+ * b\n auto R = qr.matrixQR().topRows(5).transpose().template triangularView();\n b = qr.colsPermutation().transpose()* b;\n R.solveInPlace(b);\n VectorXd x = Q.leftCols(5) * b; // just checking the result\n std::cout << \"x = \" << x.transpose() << std::endl;\n std::cout << \"||A*x-b0|| = \" << (A * x - b0).norm() << std::endl; // for comparison, the solve of CompleteOrthogonalDecomposition does a pseudo-inverse\n MatrixXd pinvA = A.completeOrthogonalDecomposition().pseudoInverse();\n VectorXd x0 = pinvA * b0; std::cout << \"x0 = \" << x0.transpose() << std::endl;\n std::cout << \"||A*x0-b0|| = \" << (A * x0 - b0).norm() << std::endl;\n std::cout << \"||x - x0|| = \" << (x0 - x).norm() << std::endl;\n}\n\nvoid func2(void) {\n using namespace std;\n MatrixXd A = MatrixXd::Random(5, 8);\n VectorXd b = VectorXd::Random(5);\n VectorXd b0 = b; //save b because we are going to write over during computations // You should have already done something like this.\n ColPivHouseholderQR qr(A.transpose());\n MatrixXd Q = qr.matrixQ(); // This computes A^+ * b\n MatrixXd R = qr.matrixR();\n MatrixXd P = qr.colsPermutation();\n double rank = qr.rank();\n\n MatrixXd R_upper = R.topRows(rank);\n auto RT = R_upper.transpose().template triangularView();\n MatrixXd PT = P.transpose();\n RT.solveInPlace(PT);\n cout << \"A * (Q*R^(-T)*P^T)\" << endl;\n cout << A*(Q.leftCols(rank)*PT) << endl;\n\n MatrixXd pinvA = A.completeOrthogonalDecomposition().pseudoInverse();\n VectorXd x0 = pinvA * b0;\n cout << \"Psuedo Inverse A : \" << endl;\n cout << pinvA << endl;\n cout << \"(Q*R^(-T)*P^T) : \" << endl;\n cout << Q.leftCols(rank)*PT << endl;\n}\n\nint main()\n{\n func1();\n func2();\n}\n", "meta": {"hexsha": "3c7f3630becf55489db710bf4b77607ad4dd164d", "size": 2111, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pseudo_inverse_qr.cpp", "max_stars_repo_name": "RyodoTanaka/eigen_example", "max_stars_repo_head_hexsha": "55da46919e02d0eb7cbea9da97ffa0f9067a6d98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pseudo_inverse_qr.cpp", "max_issues_repo_name": "RyodoTanaka/eigen_example", "max_issues_repo_head_hexsha": "55da46919e02d0eb7cbea9da97ffa0f9067a6d98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pseudo_inverse_qr.cpp", "max_forks_repo_name": "RyodoTanaka/eigen_example", "max_forks_repo_head_hexsha": "55da46919e02d0eb7cbea9da97ffa0f9067a6d98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-30T03:32:04.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-30T03:32:04.000Z", "avg_line_length": 38.3818181818, "max_line_length": 154, "alphanum_fraction": 0.6371387968, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693659780479, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.7808078282280038}} {"text": "// { Driver Code Starts\n//Initial template for C++\n\n#include \nusing boost::multiprecision::cpp_int; // https://www.geeksforgeeks.org/factorial-large-number-using-boost-multiprecision-library/\nusing namespace std;\n\n\n // } Driver Code Ends\n//User function template for C++\n\n\nclass Solution\n{\n public:\n \n // Catalan series: 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, … \n // Formulae to get the series: C0 = 0, C(N+1) = sum0ToN(Ci*C(N-i))\n \n \n //Function to find the nth catalan number.\n \n cpp_int nthCatalan(int n){\n vector dp(n+1,0);\n \n for(int i=0;i>t;\n\twhile(t--) {\n\t \n\t //taking nth number\n\t int n;\n\t cin>>n;\n\t Solution obj;\n\t //calling function findCatalan function\n\t cout<< obj.findCatalan(n) <<\"\\n\"; \n\t}\n\treturn 0;\n} // } Driver Code Ends\n", "meta": {"hexsha": "34d9b542d833f13b9ee75d8c3f5baf6ee7151bf4", "size": 1280, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Dynamic Programming/5nthCatalanNumber.cpp", "max_stars_repo_name": "Coderangshu/450DSA", "max_stars_repo_head_hexsha": "fff6cee65f75e5a0bb61d5fd8d000317a7736ca3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-18T14:51:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-18T14:51:20.000Z", "max_issues_repo_path": "Dynamic Programming/5nthCatalanNumber.cpp", "max_issues_repo_name": "Coderangshu/450DSA", "max_issues_repo_head_hexsha": "fff6cee65f75e5a0bb61d5fd8d000317a7736ca3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Dynamic Programming/5nthCatalanNumber.cpp", "max_forks_repo_name": "Coderangshu/450DSA", "max_forks_repo_head_hexsha": "fff6cee65f75e5a0bb61d5fd8d000317a7736ca3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3174603175, "max_line_length": 130, "alphanum_fraction": 0.53515625, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229959153748, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7807970348990804}} {"text": "#include \n#include \nusing namespace std;\n\n//#include \n#include \n//#include \n// 稠密矩阵的代数运算 逆矩阵,特征值\n#include \"/usr/include/eigen3/Eigen/Dense\"\n#include \"/usr/include/eigen3/Eigen/Core\"\n\n#define MATRIX_SIZE (50)\n\nint main(int argc, char **argv){\n\t\n\tEigen::Matrix matrix_23;\n\t/* Vertor3D is double 3,1, 三维坐标就相当于矩阵中1行3列 */\n\tEigen::Vector3d v_3d;\n\t/* matrxi3d is doule 3,3 */\n//\tEigen::Matrix3d matrix_33 = Eigen::Matrix3d::Zero();\n\t/* 特殊类型 */\n\tEigen::MatrixXd matrix_x;\n\t\n\tmatrix_23 << 1,1,2,2,5,5;\n\tcout << matrix_23 < wrong_type = matrix_23;\n//\tEigen::Matrix cast_type = matrix_23.cast();\n\tEigen::Matrix cast_type = matrix_23.cast() * v_3d;\n\tcout << cast_type << endl;\n\n\t/* 四则运算 */\n\tEigen::Matrix3d matrix_3d = Eigen::Matrix3d::Random();\n\tmatrix_3d << 1,2,0,0,2,3,1,0,3;\n\tcout << \"---------------\" << endl << matrix_3d << endl;\n\n\tcout << \"-------transpose--------\" << endl << matrix_3d.transpose() << endl;\n\tcout << \"-------sum--------\" << endl << matrix_3d.sum() << endl; \n\tcout << \"-------trace--------\" << endl << matrix_3d.trace() << endl;\n\tcout << \"-------multiple--------\" << endl << matrix_3d*96 << endl;\n\tcout << \"-------inverse--------\" << endl << matrix_3d.inverse() << endl;\n\tcout << \"-------[ 1 ]--------\" << endl << matrix_3d.inverse()*matrix_3d << endl;\n\tcout << \"-------determinant------\" << endl << matrix_3d.determinant() << endl;\n\n\tmatrix_3d = Eigen::Matrix3d::Random();\n\tcout << \"-------eigen random:\" << endl << matrix_3d << endl;\n\tEigen::SelfAdjointEigenSolver solver(matrix_3d.transpose()*matrix_3d);\n\tcout << \"-------eigen tra*mat:\" << endl << matrix_3d.transpose()*matrix_3d << endl;\n\tcout << \"-------eigen values:\" << endl << solver.eigenvalues() << endl;\n\tcout << \"-------eigen vector\" << endl << solver.eigenvectors() << endl;\n//\tEigen::Matrix Matrix_MM = Eigen::Matrix::Random(); //eigen default size is 50\n\t//Eigen::Matrix Matrix_MM = Eigen::Matrix::Random(); //eigen default size is 50\n\t//Eigen::Matrix v_M = Eigen::Matrix::Random();\n\t//cout << \"-------Matrix_MM:\" << endl << Matrix_MM << endl;\n\t/* 求逆 */\n\tclock_t time_st = clock();\n//\tcout << \"-------Result:\" << endl << Matrix_MM.inverse()*v_M << endl;\n//\tcout << \"-------Timest:\" << endl << 1000*(clock()-time_st)/(double)CLOCKS_PER_SEC < v_D = Eigen::Matrix::Random();\n\t//Eigen::Matrix< double,Eigen::Dynamic,Eigen::Dynamic> matrix_dynamic;\n\tEigen::Matrix< double, 100, 100> matrix_dynamic;\n\tmatrix_dynamic = Eigen::Matrix::Random();\n\ttime_st = clock();\n\tcout << \"-------Result:\" << endl << matrix_dynamic.colPivHouseholderQr().solve(v_D).transpose() << endl;\n\tcout << \"-------Timest:\" << endl << 1000*(clock()-time_st)/(double)CLOCKS_PER_SEC <\n// silence any posit arithmetic exceptions: this basically enables a silent signalling NaR\n#define POSIT_THROW_ARITHMETIC_EXCEPTION 0\n#include \n\n/* concepts\n The complete definition of a template function or class should contain the list of required\n concepts as is done for functions in the Standard template Library; see http://www.sgi.com/tech/stl/\n\n */\ntemplate \nclass forward_difference {\npublic:\n\tforward_difference(const F& f, const T& h) : f(f), h(h) {}\n\tT operator()(const T& x) const { return (f(x+h) - f(x)) / h; }\nprivate:\n\tconst F& f;\n\tT h;\n};\n\ntemplate\nclass backward_difference {\npublic:\n\tbackward_difference(const F& f, const T& h) : f(f), h(h) {}\n\tT operator()(const T& x) const { return (f(x) - f(x - h)) / h; }\nprivate:\n\tconst F& f;\n\tT h;\n};\n\ntemplate\nclass central_difference {\npublic:\n\tcentral_difference(const F& f, const T& h) : f(f), h(h) {}\n\tT operator()(const T& x) const { return (f(x + T(0.5)*h) - f(x - T(0.5)*h)) / h; }\nprivate:\n\tconst F& f;\n\tT h;\n};\n\n// Use recursion to define arbitrary n-th order derivatives\n\ntemplate\nclass nth_derivative {\n\tusing n_minus_1_derivative = nth_derivative;\npublic:\n\tnth_derivative(const F& f, const T& h) : h(h), fprev(f, h) {}\n\tT operator()(const T& x) const { return (fprev(x + h) - fprev(x)) / h; }\nprivate:\n\tn_minus_1_derivative fprev;\n\tT h;\n};\n\n// termination condition\ntemplate\nclass nth_derivative<1, F, T> : public forward_difference {\n\tusing forward_difference::forward_difference;\n};\n\n/*\n Define sine/cosine/tangent functors to use.\n Depending on the provided type, the sin(x)/cos(x)/tan(x) functions\n are ADL matched to functions in different namespaces.\n For regular float/double/long double these trigonometry functions\n will be provided by the std namespace.\n For the sw::unum posit/valid types, these functions will be provided\n by the sw::unum namespace.\n */\n\n// trigonometry sine functor\ntemplate\nstruct sine_f {\n\tT operator() (const T& x) const { return sin(x); }\n};\n\n// a functor with a scale parameter\ntemplate\nclass scaled_sine_f {\npublic:\n\tscaled_sine_f(const T& scale) : scale(scale) {}\n\tT operator() (const T& x) const { return scale * sin(x); }\nprivate:\n\tT scale;\n};\n\n// trigonometry cosine functor\ntemplate\nstruct cosine_f {\n\tT operator() (const T& x) const { return cos(x); }\n};\n\n// trigonometry tangent functor\ntemplate\nstruct tangent_f {\n\tT operator() (const T& x) const { return tan(x); }\n};\n\ntemplate\nvoid EnumerateFirstDerivativeError(const Real& x) {\n\tusing namespace std;\n\tusing namespace sw::unum; // for m_pi_4\n\n\tcout << \"sin at \" << double(x) << \" : \" << sine_f()(x) << endl;\n\tcout << \"cos at \" << double(x) << \" : \" << cosine_f()(x) << endl;\n//\tcout << \"tan at \" << double(x) << \" : \" << tan_f()(x) << endl;\n\n\tusing forward_sin_f = forward_difference, Real>;\n\tusing backward_sin_f = backward_difference, Real>;\n\tusing central_sin_f = central_difference, Real>;\n\n\tconstexpr int WIDTH = 16;\n\n\tcout << \"Finite Difference approximation of the first derivative of the function sine(x)\\n\";\n\tcout << \"Using \" << typeid(Real).name() << endl;\n\tReal h = Real(0.05);\n\tsine_f sin_o;\n\tcout << setw(WIDTH) << \"step (h)\" << setw(WIDTH) << \"backward\" << setw(WIDTH) << \"error\" << setw(WIDTH) << \"forward\" << setw(WIDTH) << \"error\" << setw(WIDTH) << \"central\" << setw(WIDTH) << \"error\\n\";\n\tfor (unsigned i = 0; i < 10; ++i) {\n\t\t// backward = left\n\t\tbackward_sin_f ld_sin_o(sin_o, h);\n\t\tReal ld_sin = ld_sin_o(x);\n\t\tReal lerror = ld_sin - cos(x);\n\n\t\t// forward = right\n\t\tforward_sin_f rd_sin_o(sin_o, h);\n\t\tReal rd_sin = rd_sin_o(x);\n\t\tReal rerror = rd_sin - cos(x);\n\n\t\t// central = middle\n\t\tcentral_sin_f md_sin_o(sin_o, h);\n\t\tReal md_sin = md_sin_o(x);\n\t\tReal merror = md_sin - cos(x);\n\n\t\tcout << setw(WIDTH) << h << setw(WIDTH) << ld_sin << setw(WIDTH) << lerror << setw(WIDTH) << rd_sin << setw(WIDTH) << rerror << setw(WIDTH) << md_sin << setw(WIDTH) << merror << endl;\n\n\t\th *= 0.5;\n\t}\n}\n\ntemplate\nvoid EnumerateSecondDerivativeError(const Real& x) {\n\tusing namespace std;\n\tusing namespace sw::unum; // for m_pi_4\n\n\tcout << \"sin at \" << double(x) << \" : \" << sine_f()(x) << endl;\n\tcout << \"cos at \" << double(x) << \" : \" << cosine_f()(x) << endl;\n\t//\tcout << \"tan at \" << double(x) << \" : \" << tan_f()(x) << endl;\n\n\tusing forward_2nd_sin_f = nth_derivative<2, sine_f, Real>;\n\t//using backward_2nd_sin_f = backward_difference, Real>;\n\t//using central_2nd_sin_f = central_difference, Real>;\n\n\tconstexpr int WIDTH = 16;\n\n\tcout << \"Finite Difference approximation of the second derivative of the function sine(x)\\n\";\n\tcout << \"Using \" << typeid(Real).name() << endl;\n\tReal h = Real(0.05);\n\tsine_f sin_o;\n\tcout << setw(WIDTH) << \"step (h)\" << setw(WIDTH) << \"backward\" << setw(WIDTH) << \"error\" << setw(WIDTH) << \"forward\" << setw(WIDTH) << \"error\" << setw(WIDTH) << \"central\" << setw(WIDTH) << \"error\\n\";\n\tfor (unsigned i = 0; i < 10; ++i) {\n\t\t// backward = left\n//\t\tbackward_sin_f ld_sin_o(sin_o, h);\n\t\tReal ld2_sin = NAN; // ld2_sin_o(x);\n\t\tReal lerror = ld2_sin + sin(x);\n\n\t\t// forward = right\n\t\tforward_2nd_sin_f rd2_sin_o(sin_o, h);\n\t\tReal rd2_sin = rd2_sin_o(x);\n\t\tReal rerror = rd2_sin + sin(x);\n\n\t\t// central = middle\n//\t\tcentral_sin_f md_sin_o(sin_o, h);\n\t\tReal md2_sin = NAN; // md2_sin_o(x);\n\t\tReal merror = md2_sin + sin(x);\n\n\t\tcout << setw(WIDTH) << h << setw(WIDTH) << ld2_sin << setw(WIDTH) << lerror << setw(WIDTH) << rd2_sin << setw(WIDTH) << rerror << setw(WIDTH) << md2_sin << setw(WIDTH) << merror << endl;\n\n\t\th *= 0.5;\n\t}\n}\n\ntemplate\nvoid EnumerateThirdDerivativeError(const Real& x) {\n\tusing namespace std;\n\tusing namespace sw::unum; // for m_pi_4\n\n\tcout << \"sin at \" << double(x) << \" : \" << sine_f()(x) << endl;\n\tcout << \"cos at \" << double(x) << \" : \" << cosine_f()(x) << endl;\n\t//\tcout << \"tan at \" << double(x) << \" : \" << tan_f()(x) << endl;\n\n\tusing forward_3rd_sin_f = nth_derivative<3, sine_f, Real>;\n\t//using backward_2nd_sin_f = backward_difference, Real>;\n\t//using central_2nd_sin_f = central_difference, Real>;\n\n\tconstexpr int WIDTH = 16;\n\n\tcout << \"Finite Difference approximation of the 3rd derivative of the function sine(x)\\n\";\n\tcout << \"Using \" << typeid(Real).name() << endl;\n\tReal h = Real(0.05);\n\tsine_f sin_o;\n\tcout << setw(WIDTH) << \"step (h)\" << setw(WIDTH) << \"backward\" << setw(WIDTH) << \"error\" << setw(WIDTH) << \"forward\" << setw(WIDTH) << \"error\" << setw(WIDTH) << \"central\" << setw(WIDTH) << \"error\\n\";\n\tfor (unsigned i = 0; i < 10; ++i) {\n\t\t// backward = left\n//\t\tbackward_sin_f ld_sin_o(sin_o, h);\n\t\tReal ld3_sin = NAN; // ld3_sin_o(x);\n\t\tReal lerror = ld3_sin + cos(x);\n\n\t\t// forward = right\n\t\tforward_3rd_sin_f rd3_sin_o(sin_o, h);\n\t\tReal rd3_sin = rd3_sin_o(x);\n\t\tReal rerror = rd3_sin + cos(x);\n\n\t\t// central = middle\n//\t\tcentral_sin_f md_sin_o(sin_o, h);\n\t\tReal md3_sin = NAN; // md2_sin_o(x);\n\t\tReal merror = md3_sin + cos(x);\n\n\t\tcout << setw(WIDTH) << h << setw(WIDTH) << ld3_sin << setw(WIDTH) << lerror << setw(WIDTH) << rd3_sin << setw(WIDTH) << rerror << setw(WIDTH) << md3_sin << setw(WIDTH) << merror << endl;\n\n\t\th *= 0.5;\n\t}\n}\n\n// compare accuracy of first derivative using different Real types\nvoid CompareTypeAccuracyOnFirstDerivative() {\n\tusing namespace sw::unum;\n\n\tconstexpr unsigned NR_SAMPLES = 3;\n\tlong double samples[3];\n\tsamples[0] = m_pi_4;\n\tsamples[1] = m_1_pi / 3.0l; \n\tsamples[2] = m_pi_2;\n\n\tfor (unsigned i = 0; i < NR_SAMPLES; ++i) {\n\t\t{\n\t\t\tusing Real = float;\n\t\t\tEnumerateFirstDerivativeError(Real(samples[i]));\n\t\t}\n\n\t\t{\n\t\t\tusing Real = double;\n\t\t\tEnumerateFirstDerivativeError(Real(samples[i]));\n\t\t}\n\n\t\t{\n\t\t\tusing Real = posit<32, 2>;\n\t\t\tEnumerateFirstDerivativeError(Real(samples[i]));\n\t\t}\n\n\t\t{\n\t\t\tusing Real = posit<64, 3>;\n\t\t\tEnumerateFirstDerivativeError(Real(samples[i]));\n\t\t}\n\t}\n}\n\n// compare accuracy of second derivative using different Real types\nvoid CompareTypeAccuracyOnSecondDerivative() {\n\tusing namespace sw::unum;\n\n\tconstexpr unsigned NR_SAMPLES = 3;\n\tlong double samples[3];\n\tsamples[0] = m_pi_4;\n\tsamples[1] = m_1_pi / 3.0l;\n\tsamples[2] = m_pi_2;\n\n\tfor (unsigned i = 0; i < NR_SAMPLES; ++i) {\n\t\t{\n\t\t\tusing Real = float;\n\t\t\tEnumerateSecondDerivativeError(Real(samples[i]));\n\t\t}\n\n\t\t{\n\t\t\tusing Real = double;\n\t\t\tEnumerateSecondDerivativeError(Real(samples[i]));\n\t\t}\n\n\t\t{\n\t\t\tusing Real = posit<32, 2>;\n\t\t\tEnumerateSecondDerivativeError(Real(samples[i]));\n\t\t}\n\n\t\t{\n\t\t\tusing Real = posit<64, 3>;\n\t\t\tEnumerateSecondDerivativeError(Real(samples[i]));\n\t\t}\n\t}\n}\n\n// compare accuracy of third derivative using different Real types\nvoid CompareTypeAccuracyOnThirdDerivative() {\n\tusing namespace sw::unum;\n\n\tconstexpr unsigned NR_SAMPLES = 3;\n\tlong double samples[3];\n\tsamples[0] = m_pi_4;\n\tsamples[1] = m_1_pi / 3.0l;\n\tsamples[2] = m_pi_2;\n\n\tfor (unsigned i = 0; i < NR_SAMPLES; ++i) {\n\t\t{\n\t\t\tusing Real = float;\n\t\t\tEnumerateThirdDerivativeError(Real(samples[i]));\n\t\t}\n\n\t\t{\n\t\t\tusing Real = double;\n\t\t\tEnumerateThirdDerivativeError(Real(samples[i]));\n\t\t}\n\n\t\t{\n\t\t\tusing Real = posit<32, 2>;\n\t\t\tEnumerateThirdDerivativeError(Real(samples[i]));\n\t\t}\n\n\t\t{\n\t\t\tusing Real = posit<64, 3>;\n\t\t\tEnumerateThirdDerivativeError(Real(samples[i]));\n\t\t}\n\t}\n}\n\nint main() \ntry {\n\tusing namespace std;\n//\tusing namespace boost::multiprecision;\n\tusing namespace sw::unum;\n\n\t\n\tCompareTypeAccuracyOnFirstDerivative();\n\tCompareTypeAccuracyOnSecondDerivative();\n\tCompareTypeAccuracyOnThirdDerivative();\n\n\t{\n\t\tusing Real = float;\n\t\tEnumerateSecondDerivativeError(Real(m_pi_4));\n\t}\n\t\n\t{\n\t\tusing Real = float;\n\t\tEnumerateThirdDerivativeError(Real(m_pi_4));\n\t}\n\n\treturn EXIT_SUCCESS;\n}\ncatch (char const* msg) {\n\tstd::cerr << msg << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_arithmetic_exception& err) {\n\tstd::cerr << \"Uncaught posit arithmetic exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const quire_exception& err) {\n\tstd::cerr << \"Uncaught quire exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_internal_exception& err) {\n\tstd::cerr << \"Uncaught posit internal exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (std::runtime_error& err) {\n\tstd::cerr << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (...) {\n\tstd::cerr << \"Caught unknown exception\" << std::endl;\n\treturn EXIT_FAILURE;\n}\n", "meta": {"hexsha": "a8911cc7423674f9899760f236ba955a447c271b", "size": 11062, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/calculus/finite_difference.cpp", "max_stars_repo_name": "shikharvashistha/hpr-blas", "max_stars_repo_head_hexsha": "73f109d45701fc3816af0a1ecd42f11d494a6f97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-02-13T10:53:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T20:30:58.000Z", "max_issues_repo_path": "applications/calculus/finite_difference.cpp", "max_issues_repo_name": "jamesquinlan/hpr-blas", "max_issues_repo_head_hexsha": "2975b4378b36a0bdc55d0dbd4f979163f7009678", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-07-20T16:45:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-17T11:19:32.000Z", "max_forks_repo_path": "applications/calculus/finite_difference.cpp", "max_forks_repo_name": "jamesquinlan/hpr-blas", "max_forks_repo_head_hexsha": "2975b4378b36a0bdc55d0dbd4f979163f7009678", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-03-12T21:20:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T05:35:35.000Z", "avg_line_length": 29.420212766, "max_line_length": 200, "alphanum_fraction": 0.6606400289, "num_tokens": 3291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.9005297901222472, "lm_q1q2_score": 0.7807915369911284}} {"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n\n#include \n\ntypedef unsigned long long nombre;\ntypedef std::vector vecteur;\ntypedef std::pair paire;\n\nnamespace {\n typedef std::tuple triplet;\n\n long double aire(long double k) {\n long double rayon = std::abs(1.0L / k);\n return rayon * rayon * M_PIl;\n }\n\n long double iteration(std::map &apollonios) {\n long double A = 0.0L;\n std::map resultat;\n for (auto p: apollonios) {\n // k4 = k1 + k2 + k3 +/- 2*sqrt(k1.k2 + k2.k3 + k3.k1)\n auto[k1, k2, k3] = p.first;\n long double k4 = k1 + k2 + k3 + 2.0L * std::sqrt(k1 * k2 + k2 * k3 + k1 * k3);\n A += p.second * aire(k4);\n resultat[std::make_tuple(k4, k1, k2)] += p.second;\n resultat[std::make_tuple(k4, k1, k3)] += p.second;\n resultat[std::make_tuple(k4, k2, k3)] += p.second;\n }\n\n std::swap(apollonios, resultat);\n return A;\n }\n}\n\nENREGISTRER_PROBLEME(199, \"Iterative Circle Packing\") {\n // Three circles of equal radius are placed inside a larger circle such that each pair of circles is tangent to one\n // another and the inner circles do not overlap. There are four uncovered \"gaps\" which are to be filled iteratively\n // with more tangent circles.\n //\n // At each iteration, a maximally sized circle is placed in each gap, which creates more gaps for the next iteration.\n // After 3 iterations (pictured), there are 108 gaps and the fraction of the area which is not covered by circles is\n // 0.06790342, rounded to eight decimal places.\n //\n // What fraction of the area is not covered by circles after 10 iterations?\n // Give your answer rounded to eight decimal places using the format x.xxxxxxxx.\n std::map apollonios;\n\n // Théorème de Descartes : (k1 + k2 + k3 + k4)² = sqrt(k1² + k2² + k3² + k4²)\n // k4 = k1 + k2 + k3 +/- 2*sqrt(k1.k2 + k2.k3 + k3.k1)\n long double k0 = -1.0L;\n long double k1 = k0 / (3.0L - 2 * std::sqrt(3.0L)); // k1 = k2 = k3\n\n apollonios[std::make_tuple(k1, k1, k1)] = 1;\n apollonios[std::make_tuple(k1, k1, k0)] = 3;\n\n long double a0 = aire(k0);\n long double A = 3.0L * aire(k1);\n\n std::cout << std::fixed << std::setprecision(8);\n std::cout << \"Iteration 0: \" << 1.0L - A / a0 << std::endl;\n\n for (nombre n = 1; n <= 10; ++n) {\n A += iteration(apollonios);\n std::cout << \"Iteration \" << n << \": \" << 1.0L - A / a0 << std::endl;\n }\n\n long double resultat = 1.0L - A / a0;\n return std::to_fixed(resultat, 8);\n}\n", "meta": {"hexsha": "d1e6625a2037f710833462c2992781af0ad341d8", "size": 2724, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme1xx/probleme199.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/probleme199.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/probleme199.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.3661971831, "max_line_length": 121, "alphanum_fraction": 0.6031571219, "num_tokens": 867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248242542283, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7804639583728312}} {"text": "/******************************************************************************\nPrácticas de cálculo matricial de estructuras\nhttps://github.com/ingmec-ual/practicas-calculo-matricial-estructuras\n\nCopyright 2017 - Jose Luis Blanco Claraco \nUniversity of Almeria\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n1. Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright\nnotice, this list of conditions and the following disclaimer in the\ndocumentation and/or other materials provided with the distribution.\n3. Neither the name of the copyright holder nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\nComplete BSD-3-clause License: https://opensource.org/licenses/BSD-3-Clause\n******************************************************************************/\n\n#include \"libcalculomatricial.h\"\n#include \n#include \n\nint main()\n{\n\ttry \n\t{\n\t\tconst double E = 200*1e9; // Modulo de Young (Pa)\n\t\tconst double A = 2*1e-4; // Area (m^2)\n\n\t\t// Matrices de rigidez de las barras individuales en \n\t\t// coordenadas LOCALES, y convertir a globales usando:\n\t\t// T*K*T' = \n\t\t// [Ri*Kii*Rit, Ri*Kij*Rjt]\n\t\t// [Rj*Kji*Rit, Rj*Kjj*Rjt]\n\t\t// -----------------------------------------------\n\t\t// barra a:\n\t\tEigen::Matrix2d Ka_11_loc, Ka_12_loc, Ka_22_loc, Ka_11, Ka_12, Ka_22;\n\t\tcalcmat::matriz_barra_art_art(0.5 /*L*/, E, A, Ka_11_loc /*Kii*/, Ka_22_loc /*Kjj*/, Ka_12_loc /*Kij*/);\n\t\tconst double ang_a = 0.0 * M_PI / 180;\n\n\t\t{\n\t\t\tconst auto Ra_i = calcmat::matriz_rotacion2(ang_a), Ra_j = Ra_i; // En este caso Ri=Rj al ser ambas de 2x2\n\t\t\tKa_11 = Ra_i*Ka_11_loc*Ra_i.transpose();\n\t\t\tKa_22 = Ra_j*Ka_22_loc*Ra_j.transpose();\n\t\t\tKa_12 = Ra_i*Ka_12_loc*Ra_j.transpose();\n\t\t}\n\n\t\t// barra b:\n\t\tEigen::Matrix2d Kb_11_loc, Kb_13_loc, Kb_33_loc, Kb_11, Kb_13, Kb_33;\n\t\tcalcmat::matriz_barra_art_art(1.0 /*L*/, E, A, Kb_11_loc /*Kii*/, Kb_33_loc /*Kjj*/, Kb_13_loc /*Kij*/);\n\t\tconst double ang_b = 90.0 * M_PI / 180;\n\n\t\t{\n\t\t\tconst auto Rb_i = calcmat::matriz_rotacion2(ang_b), Rb_j = Rb_i; // En este caso Ri=Rj al ser ambas de 2x2\n\t\t\tKb_11 = Rb_i*Kb_11_loc*Rb_i.transpose();\n\t\t\tKb_33 = Rb_j*Kb_33_loc*Rb_j.transpose();\n\t\t\tKb_13 = Rb_i*Kb_13_loc*Rb_j.transpose();\n\t\t}\n\n\t\t// barra c:\n\t\tEigen::Matrix2d Kc_22_loc, Kc_23_loc, Kc_33_loc, Kc_22, Kc_23, Kc_33;\n\t\tcalcmat::matriz_barra_art_art( hypot(0.5,1.0) /*L*/, E, A, Kc_22_loc /*Kii*/, Kc_33_loc /*Kjj*/, Kc_23_loc /*Kij*/);\n\t\tconst double ang_c = atan2(1.0 /*y*/, -0.5 /*x*/);\n\n\t\t{\n\t\t\tconst auto R23i = calcmat::matriz_rotacion2(ang_c), R23j = R23i; // En este caso Ri=Rj al ser ambas de 2x2\n\t\t\tKc_22 = R23i*Kc_22_loc*R23i.transpose();\n\t\t\tKc_33 = R23j*Kc_33_loc*R23j.transpose();\n\t\t\tKc_23 = R23i*Kc_23_loc*R23j.transpose();\n\t\t}\n\n\t\t// Ensamblar la matriz de rigidez de la estructura:\n\t\t// -----------------------------------------------\n\t\tEigen::Matrix K;\n\t\tK.setZero(); // Initializa a todo ceros\n\n\t\tK.block<2, 2>(0, 0) = Ka_11 + Kb_11;\n\t\tK.block<2, 2>(2, 2) = Ka_22 + Kc_22;\n\t\tK.block<2, 2>(4, 4) = Kb_33 + Kc_33;\n\n\t\tK.block<2, 2>(0, 2) = Ka_12;\n\t\tK.block<2, 2>(2, 0) = Ka_12.transpose();\n\n\t\tK.block<2, 2>(0, 4) = Kb_13;\n\t\tK.block<2, 2>(4, 0) = Kb_13.transpose();\n\n\t\tK.block<2, 2>(2, 4) = Kc_23;\n\t\tK.block<2, 2>(4, 2) = Kc_23.transpose();\n\n\t\tstd::cout << \"K:\\n\" << K << std::endl << std::endl;\n\n\t\t// Resolver:\n\t\t// UL = KLL^{-1} * ( FL - KLR * UR )\n\t\t// FR = KRR * UR + KRL * UL\n\t\t// -----------------------------------------------\n\t\tconst std::array idxs_R = {0,1,3}; // gdl \"restringidos\"\n\t\tconst std::array idxs_L = {2,4,5}; // gdl \"libres\"\n\n\t\tconst auto KLL = indexing(K, idxs_L, idxs_L);\n\t\tconst auto KRR = indexing(K, idxs_R, idxs_R);\n\t\tconst auto KLR = indexing(K, idxs_L, idxs_R);\n\t\tconst auto KRL = KLR.transpose();\n\n\t\tEigen::Matrix FL; // Cargas en gdl \"libres\"\n\t\tFL << 0, 1000, 0;\n\n\t\tEigen::Matrix UR; // Desplazamientos en gdl \"restringidos\" (apoyos)\n\t\tUR << 0,0,0;\n\n\t\t// UL = KLL^{-1} * ( FL - KLR * UR )\n\t\tconst Eigen::Matrix UL = KLL.colPivHouseholderQr().solve( FL - KLR*UR );\n\n\t\t// FR = KRR * UR + KRL * UL\n\t\tconst Eigen::Matrix FR = KRR * UR + KRL * UL;\n\n\t\t// Ensamblar vector U completo:\n\t\tEigen::Matrix U;\n\t\tindexing(U, idxs_L) = UL;\n\t\tindexing(U, idxs_R) = UR;\n\n\t\tstd::cout << \"UL: \" << UL.transpose() << std::endl;\n\t\tstd::cout << \"FR: \" << FR.transpose() << std::endl;\n\t\t//std::cout << \"U: \" << U.transpose() << std::endl;\n\n\t\t// Esfuerzos en cada barra \n\t\t// f^a_loc = K_^a_loc * T^a^t * u^a (formula 3.6.4 del libro)\n\t\t// ----------------------------------------------------------------\n\t\n\t\t// Barra a:\n\t\tEigen::Matrix Ka_loc, Ta;\n\t\tKa_loc <<\n\t\t\tKa_11_loc, Ka_12_loc,\n\t\t\tKa_12_loc.transpose(), Ka_22_loc;\n\t\tTa <<\n\t\t\tcalcmat::matriz_rotacion2(ang_a), Eigen::Matrix2d::Zero(),\n\t\t\tEigen::Matrix2d::Zero(), calcmat::matriz_rotacion2(ang_a);\n\t\tconst Eigen::Vector4d ua = indexing(U, std::array{0, 1, 2, 3});\n\t\tconst Eigen::Vector4d fa = Ka_loc * Ta.transpose() * ua;\n\n\t\t// Barra b:\n\t\tEigen::Matrix Kb_loc, Tb;\n\t\tKb_loc <<\n\t\t\tKb_11_loc, Kb_13_loc,\n\t\t\tKb_13_loc.transpose(), Kb_33_loc;\n\t\tTb <<\n\t\t\tcalcmat::matriz_rotacion2(ang_b), Eigen::Matrix2d::Zero(),\n\t\t\tEigen::Matrix2d::Zero(), calcmat::matriz_rotacion2(ang_b);\n\t\tconst Eigen::Vector4d ub = indexing(U, std::array{0, 1, 4, 5});\n\t\tconst Eigen::Vector4d fb = Kb_loc * Tb.transpose() * ub;\n\n\t\t// Barra c:\n\t\tEigen::Matrix Kc_loc, Tc;\n\t\tKc_loc <<\n\t\t\tKc_22_loc, Kc_23_loc,\n\t\t\tKc_23_loc.transpose(), Kc_33_loc;\n\t\tTc <<\n\t\t\tcalcmat::matriz_rotacion2(ang_c), Eigen::Matrix2d::Zero(),\n\t\t\tEigen::Matrix2d::Zero(), calcmat::matriz_rotacion2(ang_c);\n\t\tconst Eigen::Vector4d uc = indexing(U, std::array{2, 3, 4, 5});\n\t\tconst Eigen::Vector4d fc = Kc_loc * Tc.transpose() * uc;\n\n\t\tstd::cout << std::endl << \"Esfuerzos en barras (coordenadas locales):\" << std::endl;\n\t\tstd::cout << \"fa: \" << fa.transpose() << std::endl;\n\t\tstd::cout << \"fb: \" << fb.transpose() << std::endl;\n\t\tstd::cout << \"fc: \" << fc.transpose() << std::endl;\n\n\t\treturn 0; // el programa finaliza sin errores\n\t}\n\tcatch (std::exception &e)\n\t{\n\t\tstd::cerr << e.what() << std::endl;\n\t\treturn -1;\n\t}\n}\n", "meta": {"hexsha": "b9dd7e1876adc7f158d17abd6ad58d7b2938dd19", "size": 6492, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "practica1.cpp", "max_stars_repo_name": "ingmec-ual/practica1-calculo-matricial-estructuras", "max_stars_repo_head_hexsha": "1740f098d25dd306a9eeb69978888d58af46c9b7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T13:20:22.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-09T13:20:22.000Z", "max_issues_repo_path": "practica1.cpp", "max_issues_repo_name": "ingmec-ual/practicas-calculo-matricial-estructuras", "max_issues_repo_head_hexsha": "1740f098d25dd306a9eeb69978888d58af46c9b7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "practica1.cpp", "max_forks_repo_name": "ingmec-ual/practicas-calculo-matricial-estructuras", "max_forks_repo_head_hexsha": "1740f098d25dd306a9eeb69978888d58af46c9b7", "max_forks_repo_licenses": ["BSD-3-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.6779661017, "max_line_length": 118, "alphanum_fraction": 0.6118299445, "num_tokens": 2363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158417, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7804639459357158}} {"text": "// (C) Copyright Renaud Detry 2007-2015.\n// Distributed under the GNU General Public License and under the\n// BSD 3-Clause License (See accompanying file LICENSE.txt).\n\n/** @file */\n\n#include \n\n#include \n#include \n#include \n\n#include \n\nnamespace nuklei\n{\n \n namespace la\n {\n void eigenDecomposition(Matrix3 &eVectors, Vector3& eValues, const Matrix3& sym)\n {\n coord_t data[9];\n for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j)\n data[i*3+j] = sym(i,j);\n \n gsl_matrix_view m \n = gsl_matrix_view_array (data, 3, 3);\n \n gsl_vector *eval = gsl_vector_alloc (3);\n gsl_matrix *evec = gsl_matrix_alloc (3, 3);\n \n gsl_eigen_symmv_workspace * w = \n gsl_eigen_symmv_alloc (3);\n \n gsl_eigen_symmv (&m.matrix, eval, evec, w);\n \n gsl_eigen_symmv_free (w);\n \n gsl_eigen_symmv_sort (eval, evec, \n GSL_EIGEN_SORT_ABS_DESC);\n \n for (int i = 0; i < 3; i++)\n {\n eValues[i]\n = gsl_vector_get (eval, i);\n //NUKLEI_ASSERT(eValues[i] >= 0);\n gsl_vector_view evec_i \n = gsl_matrix_column (evec, i);\n for (int j = 0; j < 3; ++j)\n eVectors(j, i) = gsl_vector_get(&evec_i.vector, j);\n }\n \n // There should be a more efficient way to do this...\n if (Vector3(eVectors.GetColumn(0)).Cross(eVectors.GetColumn(1)).Dot(eVectors.GetColumn(2)) < 0)\n eVectors.SetColumn(2, -Vector3(eVectors.GetColumn(2)));\n\n gsl_vector_free (eval);\n gsl_matrix_free (evec);\n }\n \n // The following function\n // Vector3 project(const Plane3& plane, const Vector3& point)\n // is currently defined in KernelCollectionPCA.cpp\n \n \n double determinant(const GMatrix& m)\n {\n NUKLEI_FAST_ASSERT(m.GetRows() == m.GetColumns());\n const int dim = m.GetRows();\n \n gsl_matrix *lu;\n gsl_permutation *perm;\n int signum = 0;\n \n lu = gsl_matrix_alloc(dim, dim);\n perm = gsl_permutation_alloc(dim);\n \n for (int i = 0; i < dim; ++i)\n for (int j = 0; j < dim; ++j)\n {\n gsl_matrix_set(lu, i, j, m(i,j)); \n }\n \n gsl_linalg_LU_decomp(lu, perm, &signum);\n double det = gsl_linalg_LU_det(lu, signum);\n \n gsl_matrix_free(lu);\n gsl_permutation_free(perm);\n \n return det;\n }\n \n GMatrix inverse(const GMatrix& m)\n {\n NUKLEI_FAST_ASSERT(m.GetRows() == m.GetColumns());\n const int dim = m.GetRows();\n \n gsl_matrix *lu, *inverse;\n gsl_permutation *perm;\n int signum = 0;\n \n lu = gsl_matrix_alloc(dim, dim);\n inverse = gsl_matrix_alloc(dim, dim);\n perm = gsl_permutation_alloc(dim);\n \n for (int i = 0; i < dim; ++i)\n for (int j = 0; j < dim; ++j)\n {\n gsl_matrix_set(lu, i, j, m(i,j)); \n }\n \n gsl_linalg_LU_decomp(lu, perm, &signum);\n gsl_linalg_LU_invert(lu, perm, inverse);\n \n GMatrix inv(dim, dim);\n for (int i = 0; i < dim; ++i)\n for (int j = 0; j < dim; ++j)\n {\n inv(i,j) = gsl_matrix_get(inverse, i, j); \n }\n \n gsl_matrix_free(lu);\n gsl_matrix_free(inverse);\n gsl_permutation_free(perm);\n \n return inv;\n }\n \n }\n \n std::ostream& operator<<(std::ostream &out, const GMatrix &m)\n {\n for (int i = 0; i < m.GetRows(); ++i)\n {\n for (int j = 0; j < m.GetColumns(); ++j)\n NUKLEI_ASSERT(out << m(i,j) << \" \");\n NUKLEI_ASSERT(out << \"\\n\");\n }\n out << std::flush;\n return out;\n }\n\n std::istream& operator>>(std::istream &in, GMatrix &m)\n {\n std::vector< std::vector > rows;\n std::string line;\n int ntok = -1;\n while (std::getline(in, line))\n {\n cleanLine(line);\n std::vector tokens;\n boost::split(tokens, line, boost::is_any_of(\" \"), boost::token_compress_on);\n if (tokens.front() == \"\")\n tokens.erase(tokens.begin());\n if (tokens.back() == \"\")\n tokens.pop_back();\n \n if (ntok == -1)\n ntok = tokens.size();\n else\n NUKLEI_ASSERT(ntok == tokens.size());\n \n if (tokens.size() == 0)\n break;\n \n rows.push_back(std::vector());\n for (std::vector::const_iterator i = tokens.begin();\n i != tokens.end(); ++i)\n rows.back().push_back(numify(*i));\n }\n \n m.SetSize(rows.size(), ntok);\n for (int i = 0; i < m.GetRows(); ++i)\n for (int j = 0; j < m.GetColumns(); ++j)\n m(i,j) = rows.at(i).at(j);\n \n return in;\n }\n\n\n}\n", "meta": {"hexsha": "26dbbcab8d69f3c87ae130987bac70db9002f699", "size": 4816, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libnuklei/base/LinearAlgebra.cpp", "max_stars_repo_name": "chungying/nuklei", "max_stars_repo_head_hexsha": "23db2a55a1b3260cf913d0ac10b3b27c000ae1a6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libnuklei/base/LinearAlgebra.cpp", "max_issues_repo_name": "chungying/nuklei", "max_issues_repo_head_hexsha": "23db2a55a1b3260cf913d0ac10b3b27c000ae1a6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libnuklei/base/LinearAlgebra.cpp", "max_forks_repo_name": "chungying/nuklei", "max_forks_repo_head_hexsha": "23db2a55a1b3260cf913d0ac10b3b27c000ae1a6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4615384615, "max_line_length": 102, "alphanum_fraction": 0.5336378738, "num_tokens": 1383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.8333245994514082, "lm_q1q2_score": 0.7802293273873404}} {"text": "#include \r\n#include \r\n#include \r\n#include \r\n#include \r\nusing Eigen::MatrixXd;\r\nusing Eigen::VectorXd;\r\nusing namespace std;\r\n\r\nVectorXd calculateError(VectorXd state,double gt_x,double gt_y,double gt_vx,double gt_vy){\r\n VectorXd gt(4);\r\n gt << gt_x,gt_y,gt_vx,gt_vy;\r\n VectorXd error = state-gt; \r\n return error;\r\n}\r\n\r\nMatrixXd calculateJacobian(VectorXd state){\r\n double px = state(0);\r\n double py = state(1);\r\n double vx = state(2);\r\n double vy = state(3);\r\n MatrixXd jacobian(3,4);\r\n double sqrt_power = sqrt((pow(px,2)+pow(py,2)));\r\n double constant = (px*px + py*py)*sqrt_power;\r\n jacobian << (px/sqrt_power),(py/sqrt_power),0,0,\r\n (-1*py/(pow(px,2)+pow(py,2))),(px/(pow(px,2)+pow(py,2))),0,0,\r\n py*(vx*py - vy*px)/constant, px*(px*vy - py*vx)/constant, px/sqrt_power, py/sqrt_power;\r\n return jacobian;\r\n}\r\n\r\nVectorXd radar2State(VectorXd m_radar){\r\n double r_m_rho = m_radar(0);\r\n double r_m_pi = m_radar(1);\r\n double r_m_rdot = m_radar(2);\r\n double r_m_px = r_m_rho*cos(r_m_pi);\r\n if ( r_m_px < 0.0001 ) {\r\n r_m_px = 0.0001;\r\n }\r\n double r_m_py = r_m_rho*sin(r_m_pi);\r\n if(r_m_py< 0.0001){\r\n r_m_py = 0.0001;\r\n } \r\n double r_m_vx = r_m_rdot*cos(r_m_pi);\r\n double r_m_vy = r_m_rdot*sin(r_m_pi);\r\n VectorXd r_x(4) ;\r\n r_x << r_m_px,r_m_py,r_m_vx,r_m_vy;\r\n return r_x;\r\n}\r\n \r\nint main()\r\n{ \r\n ifstream reader(\"C:\\\\DEV\\\\website\\\\data\\\\obj_pose-laser-radar-synthetic-input.txt\");\r\n int tick = -10;\r\n //Matrix for laser\r\n MatrixXd R_laser_ = MatrixXd(2, 2);//measurement noise\r\n //measurement covariance matrix - laser\r\n R_laser_ << 0.0225, 0,\r\n 0, 0.0225;\r\n\r\n MatrixXd l_H(2,4);// used to convert predicted state to measurement state, shape wise\r\n l_H << 1,0,0,0,\r\n 0,1,0,0;\r\n\r\n VectorXd l_m_x(2);//measured state\r\n\r\n //Matrix for Radar\r\n MatrixXd R_radar_ = MatrixXd(3, 3);// measurement noise\r\n //measurement covariance matrix - radar\r\n R_radar_ << 0.09, 0, 0,\r\n 0, 0.0009, 0,\r\n 0, 0, 0.09;\r\n \r\n VectorXd R_m_x(3);\r\n MatrixXd Hj(3,4);\r\n\r\n\r\n string line;\r\n string part;\r\n\r\n //Global Variables , same for laser and radar\r\n MatrixXd P(4,4);//process covariance matrix\r\n MatrixXd p_P(4,4);//predicted covariance matrix\r\n MatrixXd F(4,4);//prediction matrix\r\n F << 1,0,0,0,\r\n 0,1,0,0,\r\n 0,0,1,0,\r\n 0,0,0,1; \r\n MatrixXd Q(4,4);//process covariance matrix\r\n VectorXd y;// difference between predicted and measured\r\n MatrixXd I = MatrixXd::Identity(4,4);\r\n VectorXd x(4);//state\r\n VectorXd p_x(4);//predicted state\r\n VectorXd noise(4);//noise due to model simplicity\r\n MatrixXd S;\r\n MatrixXd K;\r\n VectorXd p_R_x(3);//state measurement in radar space\r\n\r\n char type;\r\n int count = 0;//for initializing\r\n double gt_x;//ground truth\r\n double gt_y;//ground truth\r\n double gt_vy;//ground truth\r\n double gt_vx;//ground truth\r\n\r\n double noise_ax = 9.0;//noise due to model simplicity\r\n double noise_ay = 9.0;//noise due to model simplicity\r\n \r\n long long c_timestamp;\r\n long long p_timestamp;\r\n double dt;\r\n\r\n float m_px,m_py,m_vx,m_vy;\r\n float m_rho,m_pi,m_rdot;\r\n\r\n while(getline(reader,line)){\r\n istringstream my_stream(line);\r\n my_stream>>type;\r\n if(type=='L'){\r\n my_stream>>m_px;\r\n my_stream>>m_py;\r\n l_m_x<< m_px,m_py;\r\n my_stream>>c_timestamp;\r\n //for intializing state and covariance matrix\r\n if(count==0){\r\n x <>gt_x;\r\n my_stream>>gt_y;\r\n my_stream>>gt_vx;\r\n my_stream>>gt_vy;\r\n cout<<\"Error\"<>m_rho;\r\n my_stream>>m_pi;\r\n my_stream>>m_rdot;\r\n R_m_x << m_rho,m_pi,m_rdot;\r\n my_stream>>c_timestamp;\r\n if(count==0){\r\n x = radar2State(R_m_x);\r\n P << 1, 0, 0, 0,\r\n 0, 1, 0, 0,\r\n 0, 0, 1000, 0,\r\n 0, 0, 0, 1000;\r\n p_timestamp = c_timestamp;\r\n count++;\r\n continue;\r\n }\r\n dt = (c_timestamp - p_timestamp)/1000000.0;\r\n p_timestamp = c_timestamp;\r\n F(0,2) = dt;\r\n F(1,3) = dt;\r\n noise<< (noise_ax*dt*dt/2),(noise_ay*dt*dt/2),(noise_ax*dt),(noise_ay*dt);\r\n p_x = F*x + noise;\r\n Q << (dt*dt*dt*dt*noise_ax*noise_ax/4),0,(dt*dt*dt*noise_ax*noise_ax/2),0,\r\n 0,(dt*dt*dt*dt*noise_ay*noise_ay/4),0,(dt*dt*dt*noise_ay*noise_ay/2),\r\n (dt*dt*dt*noise_ax*noise_ax/2),0,(dt*dt*noise_ax*noise_ax),0,\r\n 0,(dt*dt*dt*noise_ay*noise_ay/2),0,(dt*dt*noise_ay*noise_ay);\r\n p_P = F*P*F.transpose() + Q;\r\n double px = p_x(0);\r\n double py = p_x(1);\r\n double vx = p_x(2);\r\n double vy = p_x(3);\r\n double rho = sqrt(px*px + py*py);\r\n double theta = atan2(py, px);\r\n double rho_dot = (px*vx + py*vy) / rho;\r\n p_R_x << rho,theta,rho_dot;\r\n y = R_m_x - p_R_x;\r\n while ( y(1) > M_PI || y(1) < -M_PI ) {\r\n if ( y(1) > M_PI ) {\r\n y(1) -= M_PI;\r\n } else {\r\n y(1) += M_PI;\r\n }\r\n }\r\n Hj = calculateJacobian(p_x);\r\n S = Hj*p_P*Hj.transpose() + R_radar_;\r\n K = p_P*Hj.transpose()*S.inverse();\r\n x = p_x + K*y;\r\n P = (I-K*Hj)*p_P;\r\n my_stream>>gt_x;\r\n my_stream>>gt_y;\r\n my_stream>>gt_vx;\r\n my_stream>>gt_vy;\r\n VectorXd gt(4);\r\n gt << gt_x,gt_y,gt_vx,gt_vy;\r\n cout<<\"Error\"<\n#include \n#include \n#include \n\nusing namespace std;\n\n//Evaluate the Chebyshev polynomials up to order n in x.\nvector chebpolmult(const int &n,const double &x)\n{\n vector V={1,x};\n for (int k=1; k V;\n Eigen::MatrixXd scal(n+1,n+1);\n for (int j=0; j // for normal_distribution\n using boost::math::normal; // typedef provides default type is double.\n#include // for cauchy_distribution\n using boost::math::cauchy; // typedef provides default type is double.\n#include \n using boost::math::find_location;\n using boost::math::complement; // Needed if you want to use the complement version.\n using boost::math::policies::policy;\n\n#include \n using std::cout; using std::endl;\n#include \n using std::setw; using std::setprecision;\n#include \n using std::numeric_limits;\n//] [/find_location1]\n\nint main()\n{\n cout << \"Example: Find location (mean).\" << endl;\n try\n {\n//[find_location2\n/*`\nFor this example, we will use the standard normal distribution,\nwith mean (location) zero and standard deviation (scale) unity.\nThis is also the default for this implementation.\n*/\n normal N01; // Default 'standard' normal distribution with zero mean and \n double sd = 1.; // normal default standard deviation is 1.\n/*`Suppose we want to find a different normal distribution whose mean is shifted\nso that only fraction p (here 0.001 or 0.1%) are below a certain chosen limit\n(here -2, two standard deviations).\n*/\n double z = -2.; // z to give prob p\n double p = 0.001; // only 0.1% below z\n\n cout << \"Normal distribution with mean = \" << N01.location()\n << \", standard deviation \" << N01.scale()\n << \", has \" << \"fraction <= \" << z \n << \", p = \" << cdf(N01, z) << endl;\n cout << \"Normal distribution with mean = \" << N01.location()\n << \", standard deviation \" << N01.scale()\n << \", has \" << \"fraction > \" << z\n << \", p = \" << cdf(complement(N01, z)) << endl; // Note: uses complement.\n/*`\n[pre\nNormal distribution with mean = 0, standard deviation 1, has fraction <= -2, p = 0.0227501\nNormal distribution with mean = 0, standard deviation 1, has fraction > -2, p = 0.97725\n]\nWe can now use ''find_location'' to give a new offset mean.\n*/\n double l = find_location(z, p, sd);\n cout << \"offset location (mean) = \" << l << endl;\n/*`\nthat outputs:\n[pre\noffset location (mean) = 1.09023\n]\nshowing that we need to shift the mean just over one standard deviation from its previous value of zero.\n\nThen we can check that we have achieved our objective\nby constructing a new distribution\nwith the offset mean (but same standard deviation):\n*/\n normal np001pc(l, sd); // Same standard_deviation (scale) but with mean (location) shifted.\n/*`\nAnd re-calculating the fraction below our chosen limit.\n*/\ncout << \"Normal distribution with mean = \" << l \n << \" has \" << \"fraction <= \" << z \n << \", p = \" << cdf(np001pc, z) << endl;\n cout << \"Normal distribution with mean = \" << l \n << \" has \" << \"fraction > \" << z \n << \", p = \" << cdf(complement(np001pc, z)) << endl;\n/*`\n[pre\nNormal distribution with mean = 1.09023 has fraction <= -2, p = 0.001\nNormal distribution with mean = 1.09023 has fraction > -2, p = 0.999\n]\n\n[h4 Controlling Error Handling from find_location]\nWe can also control the policy for handling various errors.\nFor example, we can define a new (possibly unwise) \npolicy to ignore domain errors ('bad' arguments).\n\nUnless we are using the boost::math namespace, we will need:\n*/\n using boost::math::policies::policy;\n using boost::math::policies::domain_error;\n using boost::math::policies::ignore_error;\n\n/*`\nUsing a typedef is often convenient, especially if it is re-used,\nalthough it is not required, as the various examples below show.\n*/\n typedef policy > ignore_domain_policy;\n // find_location with new policy, using typedef.\n l = find_location(z, p, sd, ignore_domain_policy());\n // Default policy policy<>, needs \"using boost::math::policies::policy;\"\n l = find_location(z, p, sd, policy<>());\n // Default policy, fully specified.\n l = find_location(z, p, sd, boost::math::policies::policy<>());\n // A new policy, ignoring domain errors, without using a typedef.\n l = find_location(z, p, sd, policy >());\n/*`\nIf we want to use a probability that is the \n[link complements complement of our probability],\nwe should not even think of writing `find_location(z, 1 - p, sd)`,\nbut, [link why_complements to avoid loss of accuracy], use the complement version.\n*/\n z = 2.;\n double q = 0.95; // = 1 - p; // complement.\n l = find_location(complement(z, q, sd));\n\n normal np95pc(l, sd); // Same standard_deviation (scale) but with mean(location) shifted\n cout << \"Normal distribution with mean = \" << l << \" has \" \n << \"fraction <= \" << z << \" = \" << cdf(np95pc, z) << endl;\n cout << \"Normal distribution with mean = \" << l << \" has \" \n << \"fraction > \" << z << \" = \" << cdf(complement(np95pc, z)) << endl;\n //] [/find_location2]\n }\n catch(const std::exception& e)\n { // Always useful to include try & catch blocks because default policies \n // are to throw exceptions on arguments that cause errors like underflow, overflow. \n // Lacking try & catch blocks, the program will abort without a message below,\n // which may give some helpful clues as to the cause of the exception.\n std::cout <<\n \"\\n\"\"Message from thrown exception was:\\n \" << e.what() << std::endl;\n }\n return 0;\n} // int main()\n\n\n\n//[find_location_example_output\n/*`\n[pre\nExample: Find location (mean).\nNormal distribution with mean = 0, standard deviation 1, has fraction <= -2, p = 0.0227501\nNormal distribution with mean = 0, standard deviation 1, has fraction > -2, p = 0.97725\noffset location (mean) = 1.09023\nNormal distribution with mean = 1.09023 has fraction <= -2, p = 0.001\nNormal distribution with mean = 1.09023 has fraction > -2, p = 0.999\nNormal distribution with mean = 0.355146 has fraction <= 2 = 0.95\nNormal distribution with mean = 0.355146 has fraction > 2 = 0.05\n]\n*/\n//] [/find_location_example_output]\n", "meta": {"hexsha": "ab47dc6eaf543d3f192117f71f32837729b8dc7d", "size": 6627, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/find_location_example.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/math/example/find_location_example.cpp", "max_issues_repo_name": "mike-code/boost_1_38_0", "max_issues_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/example/find_location_example.cpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7543859649, "max_line_length": 104, "alphanum_fraction": 0.6840199185, "num_tokens": 1783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.8633916099737807, "lm_q1q2_score": 0.7798966483968772}} {"text": "#include \"fmatrix.h\"\n#include \"sfm_utils.h\"\n#include \"defines.h\"\n\n#include \n#include \n#include \n\nnamespace {\n\n void infoF(const cv::Matx33d &Fcv)\n {\n Eigen::MatrixXd F;\n copy(Fcv, F);\n\n Eigen::JacobiSVD svdf(F, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n Eigen::MatrixXd U = svdf.matrixU();\n Eigen::VectorXd s = svdf.singularValues();\n Eigen::MatrixXd V = svdf.matrixV();\n\n std::cout << \"F info:\\nF:\\n\" << F << \"\\nU:\\n\" << U << \"\\ns:\\n\" << s << \"\\nV:\\n\" << V << std::endl;\n }\n\n cv::Matx33d estimateFMatrixDLT(const cv::Vec2d *m0, const cv::Vec2d *m1, int count)\n {\n int a_rows = count;\n int a_cols = 9;\n\n Eigen::MatrixXd A(a_rows, a_cols);\n\n for (int i_pair = 0; i_pair < count; ++i_pair) {\n\n double x0 = m0[i_pair][0];\n double y0 = m0[i_pair][1];\n\n double x1 = m1[i_pair][0];\n double y1 = m1[i_pair][1];\n\n// std::cout << \"(\" << x0 << \", \" << y0 << \"), (\" << x1 << \", \" << y1 << \")\" << std::endl;\n\n A.row(i_pair) << x1*x0, x1*y0, x1, y1*x0, y1*y0, y1, x0, y0, 1.0;\n }\n\n Eigen::JacobiSVD svda(A, Eigen::ComputeFullU | Eigen::ComputeFullV);\n Eigen::VectorXd null_space = svda.matrixV().col(8);\n\n Eigen::MatrixXd F(3, 3);\n F.row(0) << null_space[0], null_space[1], null_space[2];\n F.row(1) << null_space[3], null_space[4], null_space[5];\n F.row(2) << null_space[6], null_space[7], null_space[8];\n\n Eigen::JacobiSVD svdf(F, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n Eigen::MatrixXd U = svdf.matrixU();\n Eigen::VectorXd s = svdf.singularValues();\n Eigen::MatrixXd V = svdf.matrixV();\n\n Eigen::MatrixXd S = Eigen::MatrixXd(3, 3);\n S.setZero();\n S(0, 0) = s[0];\n S(1, 1) = s[1];\n S(2, 2) = 0.0;\n\n F = U * S * V.transpose();\n\n cv::Matx33d Fcv;\n copy(F, Fcv);\n\n return Fcv;\n }\n\n // get transform matrix so that after transform centroid of points will be zero and Root Mean Square distance from centroid will be sqrt(2)\n cv::Matx33d getNormalizeTransform(const std::vector &m, bool verbose=true)\n {\n cv::Vec2d centroid(0.0, 0.0);\n\n if (m.empty()) {\n throw std::runtime_error(\"Can't normalize transform\");\n }\n\n for (int i = 0; i < (int) m.size(); ++i) {\n centroid += m[i];\n }\n\n centroid /= (double) m.size();\n\n double rms = 0;\n for (int i = 0; i < (int) m.size(); ++i) {\n cv::Vec2d d = m[i] - centroid;\n rms += d[0] * d[0] + d[1] * d[1];\n }\n rms = std::sqrt(rms / (2 * m.size()));\n\n if (rms == 0) {\n throw std::runtime_error(\"Can't normalize transform\");\n }\n\n double s = std::sqrt(2) / rms;\n\n if (verbose) {\n std::cout << \"NORMALIZE TRANSFORM: centroid = \" << centroid << \", scale = \" << s << std::endl;\n }\n\n cv::Matx33d T(s, 0.0, -s*centroid[0],\n 0.0, s, -s*centroid[1],\n 0.0, 0.0, 1.0);\n\n return T;\n }\n\n cv::Vec2d transformPoint(const cv::Vec2d &pt, const cv::Matx33d &T)\n {\n cv::Vec3d tmp = T * cv::Vec3d(pt[0], pt[1], 1.0);\n\n if (tmp[2] == 0) {\n throw std::runtime_error(\"infinite point\");\n }\n\n return cv::Vec2d(tmp[0] / tmp[2], tmp[1] / tmp[2]);\n }\n\n cv::Matx33d estimateFMatrixRANSAC(const std::vector &m0, const std::vector &m1, double threshold_px, bool verbose=true)\n {\n if (m0.size() != m1.size()) {\n throw std::runtime_error(\"estimateFMatrixRANSAC: m0.size() != m1.size()\");\n }\n\n const int n_matches = m0.size();\n\n cv::Matx33d TN0 = getNormalizeTransform(m0, verbose);\n cv::Matx33d TN1 = getNormalizeTransform(m1, verbose);\n\n std::vector m0_t(n_matches);\n std::vector m1_t(n_matches);\n for (int i = 0; i < n_matches; ++i) {\n m0_t[i] = transformPoint(m0[i], TN0);\n m1_t[i] = transformPoint(m1[i], TN1);\n }\n\n {\n// check log: centroid should become close to zero, scale close to 1\n getNormalizeTransform(m0_t, verbose);\n getNormalizeTransform(m1_t, verbose);\n }\n\n // https://en.wikipedia.org/wiki/Random_sample_consensus#Parameters\n // будет отличаться от случая с гомографией\n const int n_trials = 10000;\n\n const int n_samples = 8;\n uint64_t seed = 1;\n\n int best_support = 0;\n cv::Matx33d best_F;\n\n std::vector sample;\n for (int i_trial = 0; i_trial < n_trials; ++i_trial) {\n phg::randomSample(sample, n_matches, n_samples, &seed);\n\n cv::Vec2d ms0[n_samples];\n cv::Vec2d ms1[n_samples];\n for (int i = 0; i < n_samples; ++i) {\n ms0[i] = m0_t[sample[i]];\n ms1[i] = m1_t[sample[i]];\n }\n\n cv::Matx33d F = estimateFMatrixDLT(ms0, ms1, n_samples);\n\n // denormalize\n F = TN1.t() * F * TN0;\n\n int support = 0;\n for (int i = 0; i < n_matches; ++i) {\n // todo todo todo todo todo todo\n if (phg::epipolarTest(m0[i], m1[i], F, threshold_px) && phg::epipolarTest(m1[i], m0[i], F.t(), threshold_px))\n {\n ++support;\n }\n }\n\n if (support > best_support) {\n best_support = support;\n best_F = F;\n\n if (verbose) {\n std::cout << \"estimateFMatrixRANSAC : support: \" << best_support << \"/\" << n_matches << std::endl;\n infoF(F);\n }\n\n if (best_support == n_matches) {\n break;\n }\n }\n }\n\n if (verbose) {\n std::cout << \"estimateFMatrixRANSAC : best support: \" << best_support << \"/\" << n_matches << std::endl;\n }\n\n if (best_support == 0) {\n throw std::runtime_error(\"estimateFMatrixRANSAC : failed to estimate fundamental matrix\");\n }\n\n return best_F;\n }\n\n}\n\ncv::Matx33d phg::findFMatrix(const std::vector &m0, const std::vector &m1, double threshold_px, bool verbose) {\n return estimateFMatrixRANSAC(m0, m1, threshold_px, verbose);\n}\n\ncv::Matx33d phg::findFMatrixCV(const std::vector &m0, const std::vector &m1, double threshold_px) {\n return cv::findFundamentalMat(m0, m1, cv::FM_RANSAC, threshold_px);\n}\n\ncv::Matx33d phg::composeFMatrix(const cv::Matx34d &P0, const cv::Matx34d &P1)\n{\n // compute fundamental matrix from general cameras\n // Hartley & Zisserman (17.3 - p412)\n \n cv::Matx33d F;\n\n#define det4(a, b, c, d) \\\n ((a)(0) * (b)(1) - (a)(1) * (b)(0)) * ((c)(2) * (d)(3) - (c)(3) * (d)(2)) - \\\n ((a)(0) * (b)(2) - (a)(2) * (b)(0)) * ((c)(1) * (d)(3) - (c)(3) * (d)(1)) + \\\n ((a)(0) * (b)(3) - (a)(3) * (b)(0)) * ((c)(1) * (d)(2) - (c)(2) * (d)(1)) + \\\n ((a)(1) * (b)(2) - (a)(2) * (b)(1)) * ((c)(0) * (d)(3) - (c)(3) * (d)(0)) - \\\n ((a)(1) * (b)(3) - (a)(3) * (b)(1)) * ((c)(0) * (d)(2) - (c)(2) * (d)(0)) + \\\n ((a)(2) * (b)(3) - (a)(3) * (b)(2)) * ((c)(0) * (d)(1) - (c)(1) * (d)(0))\n\n int i, j;\n for (j = 0; j < 3; j++)\n for (i = 0; i < 3; i++) {\n // here the sign is encoded in the order of lines ~ai\n const auto a1 = P0.row((i + 1) % 3);\n const auto a2 = P0.row((i + 2) % 3);\n const auto b1 = P1.row((j + 1) % 3);\n const auto b2 = P1.row((j + 2) % 3);\n\n F(j, i) = det4(a1, a2, b1, b2);\n }\n\n#undef det4\n \n return F;\n}\n", "meta": {"hexsha": "dcfee2fbb32c9c09182ec9b1cedaa8f78f699eb9", "size": 7987, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/phg/sfm/fmatrix.cpp", "max_stars_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_stars_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/phg/sfm/fmatrix.cpp", "max_issues_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_issues_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/phg/sfm/fmatrix.cpp", "max_forks_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_forks_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0763052209, "max_line_length": 145, "alphanum_fraction": 0.4875422562, "num_tokens": 2553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7798787560479133}} {"text": "#include \n\nusing namespace std;\n\n#include \n\n#include \n\nusing namespace Eigen;\n\nint main(int argc, char **argv){\n\n MatrixXf A = MatrixXf::Random(3, 2);\n cout << \"Here is the matrix A:\\n\" << A << endl;\n VectorXf b = VectorXf::Random(3);\n cout << \"Here is the right hand side b:\\n\" << b << endl;\n \n // SVD\n clock_t time_svd = clock();\n cout << \"The least-squares solution is:\\n\"\n << A.bdcSvd(ComputeThinU | ComputeThinV).solve(b) << endl;\n cout << \"time:\"\n << 1000 * (clock() - time_svd) / (double) CLOCKS_PER_SEC << \"ms\" << endl;\n\n \n // QR\n clock_t time_qr = clock();\n cout << \"\\nThe solution using the QR decomposition is:\\n\"\n << A.colPivHouseholderQr().solve(b) << endl;\n cout << \"time:\"\n << 1000 * (clock() - time_qr) / (double) CLOCKS_PER_SEC << \"ms\" << endl;\n \n // Normal Equations\n clock_t time_normal = clock();\n cout << \"\\nThe solution using normal equations is:\\n\"\n << (A.transpose() * A).ldlt().solve(A.transpose() * b) << endl;\n cout << \"time:\"\n << 1000 * (clock() - time_normal) / (double) CLOCKS_PER_SEC << \"ms\" << endl;\n \n return 0;\n}\n", "meta": {"hexsha": "babcf2120e7bea0c08f029f6cdb55139f4c2ae49", "size": 1199, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/exercise/ex_6.cpp", "max_stars_repo_name": "carmelocs/slambook2", "max_stars_repo_head_hexsha": "2b1ca4fc4bdc6a4f673e1201d88eb15431882a45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch3/exercise/ex_6.cpp", "max_issues_repo_name": "carmelocs/slambook2", "max_issues_repo_head_hexsha": "2b1ca4fc4bdc6a4f673e1201d88eb15431882a45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch3/exercise/ex_6.cpp", "max_forks_repo_name": "carmelocs/slambook2", "max_forks_repo_head_hexsha": "2b1ca4fc4bdc6a4f673e1201d88eb15431882a45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5476190476, "max_line_length": 83, "alphanum_fraction": 0.5596330275, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075777163567, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7797678930046091}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace Eigen;\n\n\n\n//Codigo par abrir el archivo\n\nMatrixXd openData(string fileToOpen)\n{\n \n vector matrixEntries;\n ifstream matrixDataFile(fileToOpen);\n string matrixRowString;\n string matrixEntry;\n \n int matrixRowNumber = 0;\n \n \n while (getline(matrixDataFile, matrixRowString))\n {\n stringstream matrixRowStringStream(matrixRowString);\n \n while (getline(matrixRowStringStream, matrixEntry, ',')) \n {\n matrixEntries.push_back(stod(matrixEntry)); \n }\n matrixRowNumber++; \n }\n \n return Map>(matrixEntries.data(), matrixRowNumber, matrixEntries.size() / matrixRowNumber);\n \n}\n\n//Codigo para guardar el archivo en cualquier formato \n\nvoid saveData(string fileName, MatrixXd matrix)\n{\n \n const static IOFormat CSVFormat(FullPrecision, DontAlignCols, \" \", \"\\n\");\n \n ofstream file(fileName);\n if (file.is_open())\n {\n file << matrix.format(CSVFormat);\n file.close();\n }\n}\n\n\n//Inversa por Gauss Jordan\n\nvoid Print(MatrixXd a, int n, int m)\n{\n FILE *output_file;\n output_file=fopen(\"Inversa_Gauss_Jordan.txt\", \"w\");\n \n for (int i = 0; i < n; i++) {\n for (int j = n; j < m; j++) {\n fprintf(output_file,\"%.3f \", a(i,j));\n }\n fprintf(output_file,\"\\n\");\n }\n \n return;\n}\n\n\nvoid Gauss(MatrixXd m){\n \n \n \n MatrixXd I_ = MatrixXd::Identity(m.rows(),m.cols());\n \n MatrixXd C(m.rows(), m.cols()+I_.cols());\n \n C << m, I_;\n \n C.row(0).swap(C.row(m.rows() - 1));\n \n for (int i = 0; i < m.rows(); i++) {\n\n for (int j = 0; j < m.rows(); j++) {\n\n if (j != i) {\n\n float temp = C(j,i) / C(i,i);\n for (int k = 0; k < 2*m.rows(); k++) {\n\n C(j,k) -= C(i,k)*temp;\n }\n }\n }\n }\n \n \n for (int i = 0; i < m.rows(); i++) {\n\n float temp_ = C(i,i);\n \n for (int j = 0; j < 2 * m.rows(); j++) {\n\n C(i,j) = C(i,j)/temp_;\n }\n \n \n }\n\n Print(C, m.cols(), 2*m.cols());\n}\n\n//Inversa por cofactores \n\nvoid getCofactor(int** A , int** temp , int p, int q, int n)\n{\n int i = 0, j = 0;\n \n for (int row = 0; row < n; row++)\n {\n for (int col = 0; col < n; col++)\n {\n \n if (row != p && col != q)\n {\n temp[i][j++] = A[row][col];\n\n if (j == n - 1)\n {\n j = 0;\n i++;\n }\n }\n }\n }\n}\n\nint determinant(int**A, int n)\n{\n int D = 0; \n if (n == 1)\n return A[0][0];\n\n int** temp = new int* [n];\n for (int i = 0; i < n; i++) {\n temp[i] = new int[n];\n }\n\n int sign = 1; \n for (int f = 0; f < n; f++)\n {\n \n getCofactor(A, temp, 0, f, n);\n D += sign * A[0][f] * determinant(temp, n - 1);\n\n \n sign = -sign;\n }\n\n return D;\n}\n\nvoid adjoint(int** A, int** adj, int N)\n{\n \n if (N == 1)\n {\n adj[0][0] = 1;\n return;\n }\n\n \n int sign = 1;\n int** temp = new int* [N];\n for (int i = 0; i < N; i++) {\n temp[i] = new int[N];\n }\n\n for (int i = 0; i < N; i++)\n {\n for (int j = 0; j < N; j++)\n {\n \n getCofactor(A, temp, i, j, N);\n\n \n sign = ((i + j) % 2 == 0) ? 1 : -1;\n\n \n adj[j][i] = (sign) * (determinant(temp, N - 1));\n }\n }\n}\n\nMatrixXd inverse(MatrixXd m, int N)\n{ \n \n int rows = m.rows();\n int cols = m.cols();\n int** matrix = new int* [rows];\n \n for (int i = 0; i < rows; i++) \n {\n matrix[i] = new int[cols];\n }\n \n for (int i = 0; i < rows; i++)\n for (int j = 0; j < cols; j++)\n *(*(matrix + i) + j) = m(i, j);\n\n float** aux = new float* [rows];\n \n for (int i = 0; i < rows; i++) {\n aux[i] = new float[cols];\n }\n \n for (int i = 0; i < rows; i++)\n for (int j = 0; j < cols; j++)\n *(*(aux + i) + j) = m(i, j);\n \n MatrixXd mx(N, N);\n \n int det = determinant(matrix, N);\n\n int** adj = new int* [N];\n for (int i = 0; i < N; i++) \n adj[i] = new int[N]; \n adjoint(matrix, adj,N);\n for (int i = 0; i < N; i++)\n for (int j = 0; j < N; j++)\n aux[i][j] = adj[i][j] / float(det);\n\n for (int j = 0; j < N; j++) {\n for (int i = 0; i < N; i++) {\n mx(j, i) = aux[j][i];\n \n }\n }\n return mx;\n\n}\n\n//Otra forma de encontrar la inversa \n//En vez de encontrar un vecotor dinamico lo que hacemos es trabajar directamente con MatrixXd \n\n/*\n\nint determ(MatrixXd m,int n)\n {\n \n int det=0, p, h, k, i, j;\n MatrixXd temp = MatrixXd::Zero(m.rows(),m.cols());\n \n if(n==1) {\n return m(0,0);\n } \n \n else if(n==2){\n det=(m(0,0)*m(1,1)-m(0,1)*m(1,0));\n return det;\n } \n \n else {\n for(p=0;p\n#include \n#include \n#include \n#include \ntypedef std::complex Complex;\nint main(int argc, char **argv) {\n using namespace std;\n string usage = string(\"Usage: \") \n + argv[0] \n + \" [-?] [-v potential] [-k wvnumber]\";\n \n if (argc>1 && argv[1]==string(\"-?\")) {\n cout << usage << endl;\n exit (0);\n }\n\n // default values\n double v=0.5;\n double k=0.2;\n \n try {\n // overwritten by command line:\n for (int i=1; i> v;\n if (string(argv[i])==\"-k\") stream >> k;\n }\n }\n catch (exception &) {\n cout << usage << endl;\n exit (0);\n }\n\n Complex I(0,1.0);\n Complex nk=k*sqrt(Complex(1-v));\n \n Eigen::VectorXcd Y(4);\n Y(0)= -exp(-I*k);\n Y(1)= 0;\n Y(2)= -I*k*exp(-I*k);\n Y(3)= 0;\n\n Eigen::MatrixXcd A(4,4);\n // First row:\n A(0,0)= exp(I*k) ;\n A(0,1)=-exp(-I*nk) ; \n A(0,2)= -exp(I*nk) ; \n A(0,3)=0 ;\n\n // Second row:\n A(1,0)= 0 ;\n A(1,1)= exp(I*nk) ; \n A(1,2)= exp(-I*nk) ; \n A(1,3)=-exp(I*k) ;\n \n // Third row:\n A(2,0)= -I*k*exp(I*k) ;\n A(2,1)=-I*nk*exp(-I*nk); \n A(2,2)= I*nk*exp(I*nk) ; \n A(2,3)=0 ;\n\n // Fourth row:\n A(3,0)= 0 ;\n A(3,1)=I*nk*exp(I*nk) ; \n A(3,2)=-I*nk*exp(-I*nk); \n A(3,3)=-I*k*exp(I*k) ;\n\n Eigen::MatrixXcd AInv= A.inverse();\n Eigen::VectorXcd BCDF=AInv*Y;\n Complex B=BCDF(0), F=BCDF(3);\n cout << \"Complex coefficients\" << endl;\n cout << BCDF << endl;\n cout << endl;\n cout << \"Reflection coefficient : \" << norm(B) << endl;\n cout << \"Transmission coefficient: \" << norm(F) << endl;\n cout << \"Sum: \" << norm(B)+norm(F) << endl;\n\n}\n", "meta": {"hexsha": "62ca9ea6caefc7054cc2d85d18de262195b545d4", "size": 1797, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CH3/RECTBARRIER/rectbarrier.cpp", "max_stars_repo_name": "acastellanos95/AppCompPhys", "max_stars_repo_head_hexsha": "920a7ba707e92f1ef92fba9d97323863994f0b1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CH3/RECTBARRIER/rectbarrier.cpp", "max_issues_repo_name": "acastellanos95/AppCompPhys", "max_issues_repo_head_hexsha": "920a7ba707e92f1ef92fba9d97323863994f0b1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CH3/RECTBARRIER/rectbarrier.cpp", "max_forks_repo_name": "acastellanos95/AppCompPhys", "max_forks_repo_head_hexsha": "920a7ba707e92f1ef92fba9d97323863994f0b1a", "max_forks_repo_licenses": ["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.4625, "max_line_length": 66, "alphanum_fraction": 0.4791318865, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.8397339596505965, "lm_q1q2_score": 0.7796163982648868}} {"text": "//\n// Created by Harold on 2021/5/1.\n//\n\n#include \n\n#include \n\n// 2D Zero-Order Gaussian Regression Filter\n// TODO: verify\nEigen::MatrixXd RGR0_2D(Eigen::MatrixXd const& data, \n\t double lambdax = 0.25, \n\t double lambday = 0.25, \n\t double dx = 0.01,\n\t double dy = 0.01,\n\t double tol = 1e-10,\n\t unsigned max_iteration_no = 9) {\n\tauto ny = data.rows();\n\tauto nx = data.cols();\n\tdouble constant = sqrt(log(2) / 2 / EIGEN_PI / EIGEN_PI);\n\n\tunsigned iterationNo = 0;\n\tEigen::MatrixXd delta = Eigen::MatrixXd::Ones(ny, nx);\n\tdouble CBx = 1;\n\tdouble CB_old = 1;\n\n\tEigen::MatrixXd w4(ny, nx);\n\tEigen::MatrixXd r4(ny, nx);\n\n\twhile (CBx > tol) {\n\t\tfor (auto kx = 0; kx < nx; ++kx)\n\t\t\tfor (auto ky = 0; ky < ny; ++ky) {\n\t\t\t\tauto px = Eigen::VectorXd::LinSpaced(nx, 0, nx);\n\t\t\t\tauto py = Eigen::VectorXd::LinSpaced(ny, 0, ny);\n\t\t\t\tEigen::VectorXd v1 = exp(-0.5 * ((py.array() - ky) * dy / constant / lambday).array().pow(2));\n\t\t\t\tEigen::RowVectorXd v2 = exp(-0.5 * ((px.array() - kx) * dx / constant / lambdax).array().pow(2)).transpose();\n\t\t\t\tEigen::MatrixXd S = (1 / sqrt(2 * EIGEN_PI) / pow(constant, 2) / lambdax / lambday) * v1 * v2;\n\t\t\t\tEigen::MatrixXd SMOD = S / S.sum();\n\t\t\t\tw4(ky, kx) = (SMOD * data * delta).sum() / (SMOD * delta).sum();\n\t\t\t}\n\t\tr4 = data - w4;\n\t\tdouble CB_next = 4.4 * r4.array().abs().sum() / r4.size();\n\t\tCBx = abs((CB_old - CB_next) / CB_old);\n\t\tfor (auto i = 0; i < nx; i++)\n\t\t\tfor (auto j = 0; j < ny; j++) {\n\t\t\t\tif (abs(r4(j, i) / CB_next) < 1)\n\t\t\t\t\tdelta(j, i) = pow(1 - pow(r4(j, i) / CB_next, 2), 2);\n\t\t\t\telse\n\t\t\t\t\tdelta(j, i) = 0;\n\t\t\t}\n\t\tCB_old = CB_next;\n\t\t++iterationNo;\n\t\tstd::cout << \"CBx: \" << CBx << \", iteration no: \" << iterationNo << std::endl;\n\t\tif (iterationNo > max_iteration_no)\n\t\t\tbreak;\n\t}\n\treturn w4;\n}\n\n// 1D Second-Order Gaussian Regression Filter\n// w(k,p)= Ax2 + Bx + C where x = (k-p)dx\nEigen::VectorXd RGR2_1D(Eigen::VectorXd const& data, \n\t double lambdac = 0.8, \n\t double dx = 0.01, \n\t double tol = 1e-10,\n\t unsigned max_iteration_no = 29) {\n\tauto n = data.size();\n\tdouble constant = sqrt(log(2) / 2 / EIGEN_PI / EIGEN_PI);\n\tEigen::VectorXd x = Eigen::VectorXd::LinSpaced(n, 0, n) * dx;\n\n\tunsigned iterationNo = 0;\n\tEigen::VectorXd delta = Eigen::VectorXd::Ones(n);\n\tdouble CBx = 1;\n\tdouble CB_old = 1;\n\n\tEigen::Matrix3d M;\n\tEigen::Vector3d Q;\n\tEigen::Vector3d P;\n\tEigen::VectorXd w1(n);\n\tEigen::VectorXd r1(n);\n\n\twhile (CBx > tol) {\n\t\tfor (auto k = 0; k < n; k++) {\n\t\t\tauto p = Eigen::VectorXd::LinSpaced(n, 0, n);\n\t\t\tEigen::VectorXd S = (1/sqrt(2 * EIGEN_PI * EIGEN_PI)/constant/lambdac) * exp(-0.5 * ((k - p.array()) * dx / constant / lambdac).array().pow(2));\n\t\t\tS /= S.sum();\n\t\t\tx = (k - p.array()) * dx;\n\t\t\tM(0, 0) = (delta.array() * S.array() * (x.array().pow(0))).sum(); // A0\n\t\t\tM(0, 1) = (delta.array() * S.array() * (x.array().pow(1))).sum(); // A1\n\t\t\tM(0, 2) = (delta.array() * S.array() * (x.array().pow(2))).sum(); // A2\n\t\t\tM(1, 0) = M(0, 1); // A1\n\t\t\tM(1, 1) = M(0, 2); // A2\n\t\t\tM(1, 2) = (delta.array() * S.array() * (x.array().pow(3))).sum(); // A3\n\t\t\tM(2, 0) = M(0, 2); // A2\n\t\t\tM(2, 1) = M(1, 2); // A3\n\t\t\tM(2, 2) = (delta.array() * S.array() * (x.array().pow(4))).sum(); // A4\n\n\t\t\tQ(0) = (delta.array() * data.array() * S.array()).sum(); // F0\n\t\t\tQ(1) = (delta.array() * data.array() * S.array() * x.array()).sum(); // F1\n\t\t\tQ(2) = (delta.array() * data.array() * S.array() * (x.array().pow(2))).sum(); // F2\n\n\t\t\tP = M.inverse() * Q;\n\t\t\tw1(k) = P(0);\n\t\t}\n\n\t\tr1 = data - w1;\n\t\tdouble CB_next = 4.4 * r1.array().abs().sum() / r1.size();\n\t\tCBx = abs((CB_old - CB_next) / CB_old);\n\t\tfor (auto j = 0; j < n; j++)\n\t\t\tif (abs(r1(j) / CB_next) < 1)\n\t\t\t\tdelta(j) = pow(1 - pow(r1(j) / CB_next, 2), 2);\n\t\t\telse\n\t\t\t\tdelta(j) = 0;\n\t\tCB_old = CB_next;\n\t\t++iterationNo;\n\t\tstd::cout << \"CBx: \" << CBx << \", iteration no: \" << iterationNo << std::endl;\n\t\tif (iterationNo > max_iteration_no)\n\t\t\tbreak;\n\t}\n\treturn w1;\n}\n\nint main() {\n\t\n\t/*\n\tEigen::MatrixXd data(15, 15);\n\tdata.setRandom();\n\tstd::cout << data << '\\n' << std::endl;\n\tauto res = RGR0_2D(data);\n\tstd::cout << res << std::endl;\n\t*/\n\n\t/*\n\tEigen::VectorXd data1(100);\n\tdata1.setRandom();\n\tstd::cout << data1.transpose() <<'\\n' << std::endl;\n\tauto res1 = RGR2_1D(data1);\n\tstd::cout << res1.transpose() << std::endl;\n\t*/\n\n\t///*\n\tunsigned N = 20;\n\tdouble A = 2;\n\tEigen::VectorXd data1(N);\n\tfor (auto i = 0; i < N; ++i)\n\t\tdata1(i) = A * sin((EIGEN_PI / N * i)) + 0.1 * rand() / (RAND_MAX / 2) - 1;\n\n\tstd::cout << data1.transpose() << '\\n' << std::endl;\n\tauto res1 = RGR2_1D(data1);\n\tstd::cout << res1.transpose() << std::endl;\n\t//*/\n\treturn 0;\n}", "meta": {"hexsha": "41b410e936d70116171917d2f75cc617a9443a5e", "size": 4776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "drafts/robust_gaussian_regression.cpp", "max_stars_repo_name": "Harold2017/m_math", "max_stars_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-04T12:26:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T08:00:15.000Z", "max_issues_repo_path": "drafts/robust_gaussian_regression.cpp", "max_issues_repo_name": "Harold2017/m_math", "max_issues_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-03T02:50:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T06:32:29.000Z", "max_forks_repo_path": "drafts/robust_gaussian_regression.cpp", "max_forks_repo_name": "Harold2017/m_math", "max_forks_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-04T12:26:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-04T12:26:12.000Z", "avg_line_length": 31.2156862745, "max_line_length": 147, "alphanum_fraction": 0.5301507538, "num_tokens": 1776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7794472625374388}} {"text": "#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \"matplotlibcpp.h\"\n\n\nusing namespace std;\nusing namespace Eigen;\nnamespace plt = matplotlibcpp;\n\n\ntemplate \nT g(T x, T a, T b, T c)\n{\n return ceres::exp(a * x * x + b * x + c);\n}\n\n\n\nstruct CurveFittingCost {\n\n CurveFittingCost(double x, double y) : _x(x), _y(y) {}\n\n template \n bool operator() (const T* const abc, T *residuals) const\n {\n residuals[0] = T(_y) - g(T(_x), abc[0], abc[1], abc[2]);\n return true;\n }\n\n private:\n const double _x, _y;\n};\n\n\n\n\n\n\nint main(int argc, char **argv) {\n std::cout << \"Gauss-Newton \\n\";\n\n double aa = 1.0, bb = 2.0, cc = 1.0;\n double a = 2.0, b = -1.0, c = 5.5;\n\n double obs_sigma = 1.0;\n std::default_random_engine generator;\n std::normal_distribution obs_noise_distrib(0.0, obs_sigma);\n\n\n int N = 100;\n std::vector x_data(N), y_data(N);\n for (int i = 0; i < N; ++i)\n {\n x_data[i] = static_cast(i) / 100.0;\n y_data[i] = g(x_data[i], aa, bb, cc) + obs_noise_distrib(generator);\n\n }\n\n\n // Add the residual blocks\n double abc[3] = {a, b, c}; // parameters\n ceres::Problem problem;\n for (int i = 0; i < N; ++i)\n {\n problem.AddResidualBlock(\n new ceres::AutoDiffCostFunction(\n new CurveFittingCost(x_data[i], y_data[i])\n ),\n nullptr,\n abc\n );\n }\n ceres::Solver::Options options;\n options.linear_solver_type = ceres::DENSE_NORMAL_CHOLESKY;\n options.minimizer_progress_to_stdout = true;\n\n ceres::Solver::Summary summary;\n chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n ceres::Solve(options, &problem, &summary);\n chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n chrono::duration time_used = chrono::duration_cast>(t2 - t1);\n cout << \"solve time cost = \" << time_used.count() << \" seconds. \" << endl;\n\n\n\n std::cout << summary.BriefReport() << std::endl;\n std::cout << \"Estimated: \" << abc[0] << \" \" << abc[1] << \" \" << abc[2] << \"\\n\";\n\n\n\n vector final_y_data(N);\n for (int i = 0; i < N; ++i)\n {\n final_y_data[i] = g(x_data[i], abc[0], abc[1], abc[2]);\n }\n\n plt::scatter(x_data, y_data);\n std::map parameters;\n parameters[\"c\"] = \"red\";\n plt::scatter(x_data, final_y_data, 1.0, parameters);\n plt::show(); \n\n return 0;\n}\n", "meta": {"hexsha": "109a965b343aa0f9b1ff25ab96e8c756535c02df", "size": 2498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch6/curve_fitting_ceres.cpp", "max_stars_repo_name": "zinsmatt/slambook2", "max_stars_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch6/curve_fitting_ceres.cpp", "max_issues_repo_name": "zinsmatt/slambook2", "max_issues_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch6/curve_fitting_ceres.cpp", "max_forks_repo_name": "zinsmatt/slambook2", "max_forks_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3035714286, "max_line_length": 96, "alphanum_fraction": 0.6220976781, "num_tokens": 805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029487, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7789562277724055}} {"text": "/*\n MIT License\n\n Copyright (c) 2019 Yuki Koyama\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 OPTIMIZATION_TEST_FUNCTIONS_HPP_\n#define OPTIMIZATION_TEST_FUNCTIONS_HPP_\n\n#include \n#include \n#if defined(OTF_WITH_EIGEN)\n#include \n#endif\n\nnamespace otf\n{\n enum class FunctionType\n {\n Beale,\n Rosenbrock,\n Sphere,\n };\n\n inline double GetValue(const double x[], const int n, const FunctionType type)\n {\n switch (type)\n {\n case FunctionType::Beale:\n {\n assert(n == 2);\n const double a = 1.500 - x[0] + x[0] * x[1];\n const double b = 2.250 - x[0] + x[0] * x[1] * x[1];\n const double c = 2.625 - x[0] + x[0] * x[1] * x[1] * x[1];\n return a * a + b * b + c * c;\n }\n case FunctionType::Rosenbrock:\n {\n assert(n >= 2);\n double value = 0.0;\n for (int i = 0; i < n - 1; ++ i)\n {\n value += 100.0 * (x[i + 1] - x[i] * x[i]) * (x[i + 1] - x[i] * x[i]) + (1.0 - x[i]) * (1.0 - x[i]);\n }\n return value;\n }\n case FunctionType::Sphere:\n {\n double value = 0.0;\n for (int i = 0; i < n; ++ i)\n {\n value += x[i] * x[i];\n }\n return value;\n }\n }\n }\n\n inline void GetGrad(const double x[],\n const int n,\n const FunctionType type,\n double grad[])\n {\n switch (type)\n {\n case FunctionType::Beale:\n {\n assert(n == 2);\n const double a = 1.500 - x[0] + x[0] * x[1];\n const double b = 2.250 - x[0] + x[0] * x[1] * x[1];\n const double c = 2.625 - x[0] + x[0] * x[1] * x[1] * x[1];\n grad[0] = 2.0 * a * (- 1.0 + x[1]) + 2.0 * b * (- 1.0 + x[1] * x[1]) + 2.0 * c * (- 1.0 + x[1] * x[1] * x[1]);\n grad[1] = 2.0 * a * x[0] + 2.0 * b * 2.0 * x[0] * x[1] + 2.0 * c * 3.0 * x[0] * x[1] * x[1];\n return;\n }\n case FunctionType::Rosenbrock:\n {\n assert(n >= 2);\n grad[0] = - 400.0 * x[0] * (x[1] - x[0] * x[0]) + 2.0 * (x[0] - 1.0);\n for (int i = 1; i < n - 1; ++ i)\n {\n grad[i] = 200.0 * (x[i] - x[i - 1] * x[i - 1]) - 400.0 * x[i] * (x[i + 1] - x[i] * x[i]) + 2.0 * (x[i] - 1.0);\n }\n grad[n - 1] = 200.0 * (x[n - 1] - x[n - 2] * x[n - 2]);\n return;\n }\n case FunctionType::Sphere:\n {\n for (int i = 0; i < n; ++ i)\n {\n grad[i] = 2.0 * x[i];\n }\n return;\n }\n }\n }\n\n inline void GetSolution(const int n,\n const FunctionType type,\n double x[])\n {\n switch (type)\n {\n case FunctionType::Beale:\n {\n assert(n == 2);\n x[0] = 3.0;\n x[1] = 0.5;\n return;\n }\n case FunctionType::Rosenbrock:\n {\n assert(n >= 2);\n for (int i = 0; i < n; ++ i)\n {\n x[i] = 1.0;\n }\n return;\n }\n case FunctionType::Sphere:\n {\n for (int i = 0; i < n; ++ i)\n {\n x[i] = 0.0;\n }\n return;\n }\n }\n }\n\n#if defined(OTF_WITH_EIGEN)\n inline double GetValue(const Eigen::VectorXd& x, const FunctionType type)\n {\n return GetValue(x.data(), x.size(), type);\n }\n\n inline Eigen::VectorXd GetGrad(const Eigen::VectorXd& x, const FunctionType type)\n {\n Eigen::VectorXd grad(x.size());\n GetGrad(x.data(), x.size(), type, grad.data());\n return grad;\n }\n\n inline Eigen::VectorXd GetSolution(const int n, const FunctionType type)\n {\n Eigen::VectorXd x(n);\n GetSolution(n, type, x.data());\n return x;\n }\n#endif\n}\n\n#endif\n", "meta": {"hexsha": "9aaeb21176f80f7d044fc5a1ae1ceeca29097eb0", "size": 5388, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/optimization-test-functions.hpp", "max_stars_repo_name": "yuki-koyama/optimization-test-functions", "max_stars_repo_head_hexsha": "572272468849c0729603281455d836a8d6a5aec4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-28T12:04:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-28T12:04:20.000Z", "max_issues_repo_path": "include/optimization-test-functions.hpp", "max_issues_repo_name": "yuki-koyama/optimization-test-functions", "max_issues_repo_head_hexsha": "572272468849c0729603281455d836a8d6a5aec4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/optimization-test-functions.hpp", "max_forks_repo_name": "yuki-koyama/optimization-test-functions", "max_forks_repo_head_hexsha": "572272468849c0729603281455d836a8d6a5aec4", "max_forks_repo_licenses": ["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.3255813953, "max_line_length": 130, "alphanum_fraction": 0.4456198961, "num_tokens": 1448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7789482320087661}} {"text": "//\n// Created by Ferdinando Fioretto on 11/2/15.\n//\n\n#ifndef MISC_UTILS_LMATRIX_HPP\n#define MISC_UTILS_LMATRIX_HPP\n\n#include \n#include \n\n#include \n#include \n#include \n\nusing namespace boost::numeric::ublas;\n\nnamespace misc_utils\n{\n // Linear Algebra\n namespace lmatrix\n {\n\n /* Matrix inversion routine.\n Uses lu_factorize and lu_substitute in uBLAS to invert a matrix */\n template\n bool InvertMatrix(const matrix& input, matrix& inverse)\n {\n typedef permutation_matrix pmatrix;\n\n // create a working copy of the input\n matrix A(input);\n\n // create a permutation matrix for the LU-factorization\n pmatrix pm(A.size1());\n\n // perform LU-factorization\n int res = lu_factorize(A, pm);\n if (res != 0)\n return false;\n\n // create identity matrix of \"inverse\"\n inverse.assign(identity_matrix (A.size1()));\n\n // backsubstitute to get the inverse\n lu_substitute(A, pm, inverse);\n\n return true;\n }\n\n template\n matrix to_matrix(const std::vector>& other) {\n matrix ret(other.size(), other[0].size());\n for (int i=0; i\n std::vector> to_matrix(matrix& other) {\n std::vector> ret(other.size1());\n for (int i = 0; i < other.size1(); i++)\n ret[i].resize(other.size2());\n\n for (int i = 0; i < other.size1(); i++) {\n for (int j = 0; j < other.size2(); j++) {\n ret[i][j] = other.at_element(i, j);\n }\n }\n return ret;\n }\n\n template \n std::vector> prod(const std::vector>& A, const std::vector>& B) {\n matrix _A = to_matrix(A);\n matrix _B = to_matrix(B);\n matrix C = boost::numeric::ublas::prod(_A, _B);\n return to_matrix(C);\n }\n\n template \n std::vector> invert(const std::vector>& A) {\n matrix _A = to_matrix(A);\n int order = A.size();\n matrix _Z(order, order);\n InvertMatrix(_A, _Z);\n return to_matrix(_Z);\n }\n\n template \n std::vector> transpose(const std::vector>& A) {\n matrix _A = to_matrix(A);\n matrix _At = boost::numeric::ublas::trans(_A);\n return to_matrix(_At);\n }\n\n\n //template \n inline std::vector> alloc(int orderI, int orderJ) {\n std::vector> Z(orderI);\n for (int i = 0; i < orderI; i++)\n Z[i].resize(orderJ, 0.0);\n return Z;\n }\n\n template \n std::string to_string(std::vector> matrix) {\n std::string ret;\n for (int i=0; i\r\n#include \r\n#include \r\n#include \r\n#include \"spdlog/spdlog.h\"\r\n\r\nnamespace numerical {\r\nnamespace fem {\r\n/**\r\n* A linear mapping from \\f$X\\f$ to \\f$x\\f$ can be written as:\r\n*\r\n* \\f[\r\n* x = \\frac{1}{2}\\left(x_L+x_R\\right)+\\frac{1}{2}\\left(x_R-x_L\\right)X\r\n* \\f]\r\n*\r\n* @param X The local coordinate in the reference cell.\r\n* @param omega_e The left and right global coordinates of the element.\r\n* @return The global coordinate.\r\n*/\r\ntemplate \r\nT affine_mapping(T X, const T (&omega_e)[2]){\r\n T x_L = omega_e[0];\r\n T x_R = omega_e[1];\r\n return 0.5*(x_L + x_R) + 0.5*(x_R - x_L)*X;\r\n}\r\n/**\r\n* Returns the \\f$i\\f$-th Lagrange polynomial. \r\n*\r\n* \\f[\r\n* \\phi_i(x) = \\prod_{j=0, j\\neq i}^N \\frac{x-x_j}{x_i-x_j}\r\n* \\f]\r\n*\r\n* @param x The local coordinate in the reference cell.\r\n* @param i The Lagrange polynomial index.\r\n* @param nodes The interpolation nodes in the reference cell.\r\n* @return The \\f$i\\f$-th Lagrange polynomial.\r\n*/\r\ntemplate \r\nT lagrange_polynomial(T x, int i, \r\n const Eigen::Matrix& nodes){\r\n T p = 1.0;\r\n for(int j=0; j\r\nT lagrange_polynomial_first_derivative(T x, int i, \r\n const Eigen::Matrix& nodes, T h, int d=1){\r\n T p = 0.0;\r\n T denom = 1.0;\r\n T lp = lagrange_polynomial(x, i, nodes);\r\n for(int j=0; j 1\r\n denom *= (nodes[i] - nodes[j]);\r\n if(d == 1){\r\n p += 1.0;\r\n } else if(d ==2){\r\n p += (x - nodes[j]);\r\n }\r\n }\r\n }\r\n p *= 2.0 / h / denom;\r\n return p;\r\n};\r\n/**\r\n* Returns all local basis function \\f$\\phi\\f$ and their derivatives,\r\n* in physical coordinates, as functions of the local point \\f$X\\f$ in a \r\n* reference cell with \\f$d+1\\f$ nodes.\r\n*\r\n* Example:\r\n* ~~~~~~~~~~~~~~~{.cpp}\r\n* #include \"numerical/fem/FiniteElement.hpp\"\r\n*\r\n* using namespace numerical;\r\n*\r\n* int main()\r\n* {\r\n* double f0 = fem::phi(0, 0, 0.0); // basis func 0 at X=0\r\n* double fp0 = fem::phi(0, 0, 0.0); // 1st x-derivative at X=0\r\n* spdlog::info(\"f0: {}, fp0: {}\", f0, fp0);\r\n* return 0;\r\n* }\r\n* ~~~~~~~~~~~~~~~\r\n* Output:\r\n* ~~~~~~~~~~~~~~~{.sh}\r\n* $ f0: 0.5, fp0: -2.0\r\n* ~~~~~~~~~~~~~~~\r\n*\r\n* @param i 0 if function, 1 if first derivative.\r\n* @param j The index of the basis function.\r\n* @param x The local coordinate.\r\n* @param h The element size.\r\n* @param d The polynomial order.\r\n* @return The value of the basis function/derivative at the local \r\n* coordinate.\r\n*/\r\ntemplate \r\nT phi(int i, int j, T x, T h=2.0, int d=1){\r\n typedef Eigen::Matrix Vec;\r\n Vec nodes = Vec::LinSpaced(d+1, -1.0, 1.0); // local nodes\r\n if(j>d){\r\n spdlog::error(\"Invalid value, index j must be in the range [0,d].\");\r\n return 0.0;\r\n }\r\n if(std::abs(x)>1){\r\n spdlog::error(\"Invalid value, x must be in the range [-1,1].\");\r\n return 0.0;\r\n }\r\n if(i==0){ // function\r\n return lagrange_polynomial(x, j, nodes);\r\n } else if(i==1){\r\n return lagrange_polynomial_first_derivative(x, j, nodes, h, d);\r\n } else{\r\n spdlog::error(\"Invalid value, 'i' is either 0 or 1.\");\r\n return 0.0;\r\n }\r\n}\r\n/**\r\n* Return points and weights for Gauss-Legendre rules on [-1,1]. The number of \r\n* points implemented are 1-4.\r\n*\r\n* Numerical integration rules can be expressed in a common form:\r\n*\r\n* \\f[\r\n* \\int_{-1}^{1} g(X)dX\\approx \\sum_{j=0}^M w_jg(\\bar{X}_j)\r\n* \\f]\r\n*\r\n* where \\f$\\bar{X}_j\\f$ are integration points, and \\f$w_j\\f$ are integration\r\n* weights, for \\f$j=0,\\ldots ,M\\f$. \r\n*\r\n* More accurate rules, for a given \\f$M\\f$, arise if the location of the \r\n* integration points are optimized for polynomial integrands. The\r\n* Gauss-Legendre quadrature constitute one such class of integration methods. \r\n* Two widely applied Gauss-Legendre rules in this family have the choice:\r\n*\r\n* for \\f$M=1\\f$:\r\n*\r\n* \\f[\r\n* \\bar{X}_0 = -\\frac{1}{\\sqrt{3}},\\quad \\bar{X}_1 = \\frac{1}{\\sqrt{3}},\r\n* \\quad w_0=w_1=1\r\n* \\f]\r\n*\r\n* For \\f$M=2\\f$:\r\n*\r\n* \\f[\r\n* \\bar{X}_0 = -\\sqrt{\\frac{3}{5}},\\quad \\bar{X}_1 = 0,\r\n* \\quad \\bar{X}_2 = \\sqrt{\\frac{3}{5}}, \\quad w_0=w_2=\\frac{5}{9},\r\n* \\qaud w_1 = \\frac{8}{9}\r\n* \\f]\r\n*\r\n* These rules integrate 3rd and 5th degree polynomials exactly. In general,\r\n* an \\f$M\\f$-point Gauss-Legendre rule integrates a polynomial of degree \r\n* \\f$2M + 1\\f$ exactly.\r\n*\r\n* @param n The number of integration points.\r\n* @return The points and weights.\r\n*/\r\ntemplate \r\nstd::vector> GaussLegendre(int n){\r\n std::vector points;\r\n std::vector weights;\r\n if(n == 1){\r\n points = {0.0};\r\n weights = {2.0};\r\n } else if(n == 2){\r\n points = {-0.5773502691896257645091488, \r\n 0.5773502691896257645091488};\r\n weights = {1.0, 1.0};\r\n } else if(n == 3){\r\n points = {-0.7745966692414833770358531, \r\n 0.0,\r\n 0.7745966692414833770358531};\r\n weights = {0.5555555555555555555555556,\r\n 0.8888888888888888888888889,\r\n 0.5555555555555555555555556};\r\n } else if(n == 4){\r\n points = {-0.8611363115940525752239465,\r\n -0.3399810435848562648026658,\r\n 0.3399810435848562648026658,\r\n 0.8611363115940525752239465};\r\n weights = {0.3478548451374538573730639,\r\n 0.6521451548625461426269361,\r\n 0.6521451548625461426269361,\r\n 0.3478548451374538573730639};\r\n } else {\r\n spdlog::error(\"Gauss-Legendre: The number of points is not supported\");\r\n return {{}};\r\n }\r\n return {points, weights};\r\n}\r\n\r\n} // namespace fem\r\n} // namespace numerical\r\n\r\n#endif // FINITEELEMENT_H\r\n", "meta": {"hexsha": "bbd5338efc3e5c148371d10dd46a1574fb569f20", "size": 7721, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "numerical/fem/FiniteElement.hpp", "max_stars_repo_name": "frRoy/Numerical", "max_stars_repo_head_hexsha": "97e2167cf794eceaeba395bb1958fee72d8cbecf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numerical/fem/FiniteElement.hpp", "max_issues_repo_name": "frRoy/Numerical", "max_issues_repo_head_hexsha": "97e2167cf794eceaeba395bb1958fee72d8cbecf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numerical/fem/FiniteElement.hpp", "max_forks_repo_name": "frRoy/Numerical", "max_forks_repo_head_hexsha": "97e2167cf794eceaeba395bb1958fee72d8cbecf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5177865613, "max_line_length": 80, "alphanum_fraction": 0.5626214221, "num_tokens": 2561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191322715435, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.778807187894569}} {"text": "/* example for MatlabPlotter: Natural cubic splines (core problem)\n\n\tAn in-class exercise using equations for the cubic splines as\n\tshown in the lecture/manuscript for Numerical Methods for CSE\n\tby Prof. R. Hiptmair, ETH Zürich\n\n\tInclude the Eigen3 library as shown in documentation for Eigen3.\n\n\tuse piping to store the .m file. Example call:\n\tnatcsi >example.m\n\n\tgiven nodes (t_i,y_i) for i = 0,...,n\n\n\tand using eq 3.5.5, the calculation of y = s(x) boils down to\n\t- finding the correct interval [t_j-1,t_j] for x\n\t- apply s|[t_j-1,t_j](x) = s_j(x) =\n\t\ty_j-1 * (1 - 3 * tau^2 + 2 * tau^3) +\n\t\ty_j * (3 * tau^2 - 2 * tau^3) +\n\t\tm_j-1 * (tau - 2 * tau^2 + tau^3) +\n\t\tm_j * (-tau^2 + tau^3)\n\n\t\twith\n\t\tm1_j = m_j-1 = h_j * c_j-1,\n\t\tm2_j = m_j = h_j * c_j\n\t\t\n\t\tc_j = s'(t_j)\n\t\t\n\t\th_j = t_j - t_j-1\n\n\t\ttau = (t - t_j-1) / h_j\n\n\tcurrent runtime:\n\t- initialization: O(n), Thomas algorithm for solving the tridiagonal system matrix\n\t- evaluation:\n\t\t* worst case: O(log n)\n\t\t* best/typical case: O(1)\n\t\n\tspace requirements: O(n) all the time \n\n\toutput: is given again as a Matlab script that\n\tallows plotting all data in Matlab.\n\n\tv1.1.1 2015-11-05 / 2015-11-29 Pirmin Schmid \n*/\n\n#include \n#define _USE_MATH_DEFINES\n#include \n#include \n#include \n#include \"matlab_plotter.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n// cubic spline interpolant with natural boundaries\nclass NatCSI {\npublic:\n\t\n\t// build cubic spline interpolant with natural boundaries\n\t// input: t nodes of the grid for pairs (t_i, y_i), sorted!\n\t// y values y_i at t_i for pairs (t_i, y_i), sorted!\n\t// input in std::vector type\n\tNatCSI(const vector& t, const vector& y) {\n\t\t// map std::vector to a VectorXd\n\t\tVectorXd tmp_t = VectorXd::Map(t.data(), t.size());\n\t\tVectorXd tmp_y = VectorXd::Map(y.data(), y.size());\n\t\t\n\t\t// store a copy of the data\n\t\tthis->t = tmp_t;\n\t\tthis->y = tmp_y;\n\t\t\n\t\tcompute_coefficients();\n\t}\n\t\n\t// build cubic spline interpolant with natural boundaries\n\t// input: t nodes of the grid for pairs (t_i, y_i), sorted!\n\t// y values y_i at t_i for pairs (t_i, y_i), sorted!\n\t// input in Eigen::VectorXd type\n\tNatCSI(const VectorXd& t, const VectorXd& y) {\n\t\t// store a copy of the input vectors\n\t\tthis->t = t;\n\t\tthis->y = y;\n\t\t\n\t\tcompute_coefficients();\n\t}\n\t\n\t// interpolant evaluation at x\n\t// input: x value where to evaluate the spline\n\t// return: y = s(x) if x in defined range of s(x)\n\t// or 0.0 otherwise\n\tdouble operator() (double x) {\n\t\t// out of defined interval\n\t\tif(x < min || max < x) {\n\t\t\treturn 0.0;\n\t\t}\n\t\t\n\t\t// get proper j, using a heuristic\n\t\t// 1) check whether x is in last range, O(1)\n\t\t// 2) check whether x is in next range, O(1)\n\t\t// 3) use binary search tree, O(log n)\n\t\tif(!in_range(x, last_j)) {\n\t\t\tif(last_j < n && in_range(x, last_j+1)) {\n\t\t\t\t// note: the second test is only applied if last_j actually allows it\n\t\t\t\tlast_j++;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfind_index(x);\n\t\t\t}\n\t\t}\n\t\t\n\t\t// apply function in interval j\n\t\tint j = last_j; // just for convenience\n\t\t\n\t\tdouble tau = (x - t[j-1]) / h[j];\n\t\tdouble tau2 = tau * tau;\n\t\tdouble tau3 = tau2 * tau;\n\t\t\n\t\tdouble result = y[j-1] * (1.0 - 3.0 * tau2 + 2.0 * tau3);\n\t\tresult += y[j] * (3.0 * tau2 - 2.0 * tau3);\n\t\tresult += m1[j] * (tau - 2.0 * tau2 + tau3);\n\t\tresult += m2[j] * (-tau2 + tau3);\n\t\treturn result;\n\t}\n\t\nprivate:\n\t// we need to store the vectors t and y\n\t// and a vector for m and h as described above\n\t// m is calculated after having solved a LSE\n\t// A * c = d as described below (and in the manuscript)\n\t\n\tVectorXd t, y, h, m1, m2;\n\t\n\t// number of segments of the spline function\n\t// note: n is a valid index for the vectors. Their size is (n+1).\n\tint n = 0;\n\t\n\t// valid range for x\n\tdouble min = 0.0;\n\tdouble max = 0.0;\n\t\n\t// since most requests for x calculations are in vicinity\n\t// of the prior one (or even sorted), remembering\n\t// the last requested section will help to bring\n\t// evaluation time to O(1) compared to O(log n) if only\n\t// a binary search tree is used.\n\t// the binary search tree is currently used as a fallback\n\t// in case the current partition/segment or the next one\n\t// has not been successful.\n\tint last_j = 1;\n\t\n\t// returns true if x is in interval j [t_j-1, t_j]\n\tbool in_range(const double x, const int j) const {\n\t\tassert(1 <= j && j <= n);\n\t\treturn t[j-1] <= x && x <= t[j];\n\t}\n\t\n\t// sets last_j to index of matching interval j [t_j-1, t_j] if x in range\n\t// note: x had to be tested before whether it is actually within the range of the spline function\n\t// note: optimizations (first test whether last interval was already ok or test the next\n\t// interval have already been done when one calls this function)\n\t// finds next j in O(log n) time\n\tvoid find_index(const double x) {\n\t\tassert(min <= x && x <= max);\n\t\t\n\t\tint j = last_j;\n\t\tint a = 1;\n\t\tint b = n;\n\t\tbool found = false;\n\t\twhile(!found) {\n\t\t\tif(x < t[j-1]) {\n\t\t\t\tb = j;\n\t\t\t\tj = (a+b)/2;\n\t\t\t}\n\t\t\telse if(t[j] < x) { \n\t\t\t\tif(a == b-1) {\n\t\t\t\t\t// special case needed due to integer division rounding down\n\t\t\t\t\tj = b;\n\t\t\t\t\tfound = true;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ta = j;\n\t\t\t\t\tj = (a+b)/2;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// match\n\t\t\t\tfound = true;\n\t\t\t}\n\t\t}\n\t\t\n\t\tlast_j = j;\n\t}\n\t\n\tvoid compute_coefficients() {\n\t\tif(t.size() != y.size()) {\n\t\t\t// only minimalistic error management\n\t\t\tcout << \"Error: size of t and y must be identical.\" << endl;\n\t\t\texit(1);\n\t\t}\n\t\t\n\t\t// n\n\t\tn = (int)t.size() - 1;\n\t\t\n\t\t// min/max\n\t\tmin = t[0];\n\t\tmax = t[n];\n\t\t\n\t\t// h_j = t_j - t_j-i\n\t\th.resize(n + 1);\n\t\th.segment(1, n) = t.tail(n) - t.head(n);\n\t\t\n\t\t// build a virtual (n+1)x(n+1) system matrix A; however, only the diagonal vectors will actually be built\n\t\t// A = diag(a) + diag(b,1) + diag(b,-1), with size(a) = n+1 and size(b) = n\n\t\t\n\t\t// b_i = 1/h_i+1 for i=0 to n-1\n\t\tVectorXd b = h.tail(n).cwiseInverse();\n\t\t\n\t\t// a_i = 2/h_i + 2/h_i+1 for i=1 to n-1\n\t\t// a_0 = 2/h_1 (see natural cubic spline)\n\t\t// a_n = 2/h_n (see natural cubic spline)\n\t\tVectorXd a(n + 1);\n\t\ta.segment(1, n-1) = 2.0 * (h.segment(1, n-1).cwiseInverse() + h.tail(n-1).cwiseInverse());\n\t\ta[0] = 2.0 / h[1];\n\t\ta[n] = 2.0 / h[n];\n\t\t\n\t\t// right hand side d for A*c = d\n\t\t// for i=1 to n-1\n\t\t// d_i = 3.0 * ( (y_i - y_i-1) / h2_i + (y_i+1 - y_i) / h2_i+1 )\n\t\t// d_0 = 3.0 * (y_1 - y_0) / h2_1\n\t\t// d_n = 3.0 * (y_n - y_n-1) / h2_n\n\t\t\n\t\tVectorXd h2 = h.cwiseProduct(h); // h^2\n\t\t\n\t\t// note: y_i - y_i-1 is stored in delta_y[i-1]\n\t\tVectorXd delta_y = y.tail(n) - y.head(n);\n\t\t\n\t\t// quotient is either left or right side inside the brackets\n\t\tVectorXd quotient = delta_y.cwiseQuotient(h2.tail(n));\n\t\t\n\t\t// build d\n\t\tVectorXd d(n + 1);\n\t\td.segment(1, n-1) = quotient.head(n-1) + quotient.tail(n-1);\n\t\td[0] = delta_y[0] / h2[1];\n\t\td[n] = delta_y[n-1] / h2[n];\n\t\td = 3.0 * d;\n\t\t\n\t\t// Solution of this LSE with n+1 equations and n+1 unknowns c0 to cn\n\t\t// using the Thomas algorithm for tridiagonal matrices, needs O(n)\n\t\t// typical description with vectors b1..bn, a2..an, c1..cn-1\n\t\t// 'b' is a here\n\t\t// 'a' and 'c' are b here\n\t\t// 'x' is our c\n\t\t// note: different indices, too; also we have size n+1 instead of n\n\t\t\n\t\t// forward preparation\n\t\tVectorXd bprime(n);\n\t\tVectorXd dprime(n+1);\n\t\t\n\t\t// cprime -> bprime\n\t\tbprime[0] = b[0] / a[0];\n\t\tfor(int i = 1; i < (n-1); ++i) {\n\t\t\tbprime[i] = b[i] / (a[i] - bprime[i-1] * b[i]);\n\t\t}\n\t\t\n\t\t// dprime\n\t\tdprime[0] = d[0] / a[0];\n\t\tfor(int i = 1; i < n; ++i) {\n\t\t\tdprime[i] = (d[i] - dprime[i-1] * b[i]) / (a[i] - bprime[i-1] * b[i]);\n\t\t}\n\t\t\n\t\t// back substitution to get x, or c in our case\n\t\tVectorXd c(n + 1);\n\t\tc[n] = dprime[n];\n\t\tfor(int i = n-1; i >= 0; --i) {\n\t\t\tc[i] = dprime[i] - bprime[i] * c[i+1];\n\t\t}\n\t\t\n\t\t// we do not actually need c but\n\t\t// m1_j = m_j-1 = h_j * c_j-1,\n\t\t// m2_j = m_j = h_j * c_j\n\t\tm1.resize(n+1);\n\t\tm2.resize(n+1);\n\t\tm1.segment(1, n) = h.tail(n).cwiseProduct( c.head(n) );\n\t\tm2.segment(1, n) = h.tail(n).cwiseProduct( c.tail(n) );\n\t}\n\t\n};\n\n// just a quick implementation of the function\ndouble f(const double x) {\n\treturn exp(sin(2.0 * M_PI * x));\n}\n\n#define MIN -3\n#define MAX 3\n#define N_T 61\n#define N_X 600\n\nint main() {\n\t// initialization\n\tVectorXd t = VectorXd::LinSpaced(N_T, MIN, MAX);\n\tVectorXd y(N_T);\n\tfor(int i = 0; i < N_T; ++i) {\n\t\ty[i] = f(t[i]);\n\t}\n\t\n\tNatCSI ncsi(t, y);\n\t\n\t// test 1\n\tVectorXd xx = VectorXd::LinSpaced(N_X, MIN, MAX);\n\tVectorXd yy(N_X);\n\tfor(int i = 0; i < N_X; ++i) {\n\t\tyy[i] = ncsi(xx[i]);\n\t}\n\t\n\t// test 2. test the binary search in find_index()\n\tVectorXd y2(N_T);\n\tfor(int i = N_T-1; i >= 0; --i) {\n\t\ty2[i] = ncsi(t[i]);\n\t}\n\t\n\t// test 3. test border case (last node)\n\t// make sure that the 1st AND the last node are highlighted\n\t// in the plot (last node: see special case handling due to\n\t// integer division in find_index() )\n\tVectorXd x3(2);\n\tVectorXd y3(2);\n\tx3 << t[0], t[N_T-1];\n\tfor(int i = 0; i < x3.size(); ++i) {\n\t\ty3[i] = ncsi(x3[i]);\n\t}\n\t\n\t// test 4. test std::vector (no legend item)\n\tvector x4 = {MIN, MAX};\n\tvector y4 = {1.0, 1.0};\n\n\t// plot results\n\tMatlabPlotter p;\n\tp.comment(\"Example: natural cubic splines\");\n\tp.comment(\"Code generated by natcsi.cpp\");\n\tp.figure(\"Natural CSI\");\n\tp.plot_fx(\"exp(sin(2.*pi.*x))\", MIN, MAX, N_X, \"b-\");\n\tp.hold();\n\tp.plot(t, y, \"b*\");\n\tp.plot(xx, yy, \"r--\");\n\tp.plot(t, y2, \"ro\");\n\tp.plot(x3, y3, \"g*\");\n\tp.plot(x4, y4, \"k:\");\n\tp.xylabels(\"x\", \"y\");\n\tp.legend(\"exp(sin(2*pi*x))\", \"t0 to tn\", \"Natural CSI\", \"check findindex()\", \"check corner cases\");\n\tp.hold(false);\n\n\t// for testing / illustration purpose: semilog scale for y axis\n\tp.figure(\"Natural CSI. semilog scale\", MatlabPlotter::SEMILOGY);\n\tp.plot_fx(\"exp(sin(2.*pi.*x))\", MIN, MAX, N_X, \"b-\");\n\tp.hold();\n\tp.plot(t, y, \"b*\");\n\tp.plot(xx, yy, \"r--\");\n\tp.plot(t, y2, \"ro\");\n\tp.plot(x3, y3, \"g*\");\n\tp.plot(x4, y4, \"k:\");\n\tp.xylabels(\"x\", \"y (log scale)\");\n\tp.legend(\"exp(sin(2*pi*x))\", \"t0 to tn\", \"Natural CSI\", \"check findindex()\", \"check corner cases\");\n\tp.hold(false);\n}\n", "meta": {"hexsha": "50934c8de80119cad79b3979a73a8c8ed3477ab6", "size": 9963, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/natcsi.cpp", "max_stars_repo_name": "pirminschmid/MatlabPlotter", "max_stars_repo_head_hexsha": "6cdc3954ee4a065d978c0248b00406366eafe237", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-11-09T13:21:08.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-09T15:54:38.000Z", "max_issues_repo_path": "example/natcsi.cpp", "max_issues_repo_name": "pirminschmid/MatlabPlotter", "max_issues_repo_head_hexsha": "6cdc3954ee4a065d978c0248b00406366eafe237", "max_issues_repo_licenses": ["MIT"], "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/natcsi.cpp", "max_forks_repo_name": "pirminschmid/MatlabPlotter", "max_forks_repo_head_hexsha": "6cdc3954ee4a065d978c0248b00406366eafe237", "max_forks_repo_licenses": ["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.1471389646, "max_line_length": 107, "alphanum_fraction": 0.5946000201, "num_tokens": 3574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8807970826714614, "lm_q1q2_score": 0.7786592257108149}} {"text": "\n#include \n\nusing namespace Eigen;\n\t\nnamespace Geometry\n{\n\n\t/// Compute the pseudo-inverse of a matrix\n\tEigen::MatrixXd pseudoInverse(const Eigen::MatrixXd& A)\n\t{\n\t\tJacobiSVD svd(A, ComputeFullU | ComputeFullV);\n\t\tdouble tolerance=1e-6;\n\t\tint u=(int)A.rows(), v=(int)A.cols(), n=std::min(u,v);\n\t\tMatrixXd sigma(v,u);\n\t\tsigma.setZero();\n\t\tsigma.topLeftCorner(n,n)=svd.singularValues().asDiagonal();\n\t\tfor (int i=0;i& P, Eigen::Matrix& Pinv, Eigen::Vector4d& C)\n\t{\n\t\tJacobiSVD svd(P, ComputeFullU | ComputeFullV);\n\t\tdouble tolerance=1e-6;\n\t\tint u=(int)P.rows(), v=(int)P.cols(), n=std::min(u,v);\n\t\tMatrixXd sigma(v,u);\n\t\tsigma.setZero();\n\t\tsigma.topLeftCorner(n,n)=svd.singularValues().asDiagonal();\n\t\tfor (int i=0;i svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\t\tauto V=svd.matrixV();\n\t\treturn V.col(V.cols()-1);\n\t}\n\n\t// Enforce rank deficiency\n\tEigen::MatrixXd makeRankDeficient(const Eigen::MatrixXd& A)\n\t{\n\t\tJacobiSVD svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\t\tVectorXd sigma=svd.singularValues();\n\t\tsigma[sigma.size()-1]=0;\n\t\treturn svd.matrixU()*sigma.asDiagonal()*svd.matrixV().transpose();\n\t}\n\t\n\t// Compute left null-space of A\n\tEigen::VectorXd nullspace_left(const Eigen::MatrixXd& A)\n\t{\n\t\treturn nullspace(A.transpose());\n\t}\n\t\n} // namespace Geometry\n", "meta": {"hexsha": "b13f0d1fd2fb041ad885e3dd30411c0d227d344e", "size": 1933, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/LibProjectiveGeometry/SingularValueDecomposition.cpp", "max_stars_repo_name": "mareikethies/EpipolarConsistency", "max_stars_repo_head_hexsha": "63d7ca2fd705911a6c93ca4247486fc66a9d31c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-21T16:33:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-12T03:03:00.000Z", "max_issues_repo_path": "code/LibProjectiveGeometry/SingularValueDecomposition.cpp", "max_issues_repo_name": "mareikethies/EpipolarConsistency", "max_issues_repo_head_hexsha": "63d7ca2fd705911a6c93ca4247486fc66a9d31c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-14T07:48:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-14T07:48:55.000Z", "max_forks_repo_path": "code/LibProjectiveGeometry/SingularValueDecomposition.cpp", "max_forks_repo_name": "mareikethies/EpipolarConsistency", "max_forks_repo_head_hexsha": "63d7ca2fd705911a6c93ca4247486fc66a9d31c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-05-15T21:38:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T07:20:47.000Z", "avg_line_length": 29.2878787879, "max_line_length": 120, "alphanum_fraction": 0.682876358, "num_tokens": 624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768651485395, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7784378811529091}} {"text": "#include \"hypothesis.h\"\r\n#include \r\n#include \r\n#include \r\nusing namespace std;\r\n\r\nHypothesis::Hypothesis() = default;\r\n\r\n\r\n// Hypothesis test for the avarage, we use the library Boost to integrate the function\r\n// that corresponds for the Normal Cumulative Distribution Function, we use gaussian\r\n// quadrature method to integrate passing the lambda function that corresponds to the\r\n// Normal. We followed \"Curso de Planejamento Experimental - FEMEC - UFU\" available\r\n// on Moodle to every step to do.\r\ndouble Hypothesis::testAverage(double sampleAvg, double sampleStdDev, unsigned long sampleNumElements,\r\n double confidencelevel, double avg, H1Comparition comp) {\r\n using namespace boost::math::quadrature;\r\n\r\n double stdError = sampleStdDev / sqrt(sampleNumElements);\r\n\r\n double z_calc = (sampleAvg - avg) / stdError;\r\n\r\n auto f = [](const double &x) {\r\n double constant = 1 / sqrt(2 * M_PI);\r\n double e = exp(pow(x, 2));\r\n double sqrtE = 1 / sqrt(e);\r\n return constant * sqrtE;\r\n };\r\n\r\n double Q = gauss::integrate(f, -INFINITY, z_calc);\r\n\r\n double alpha = confidencelevel / 100;\r\n\r\n testHypothesisNull(comp, alpha, Q);\r\n return Q;\r\n\r\n}\r\n\r\n// Really similar to the previous method, we used the same things and followed\r\n// the document on Moodle.\r\ndouble Hypothesis::testProportion(double sampleProp, unsigned long sampleNumElements, double confidencelevel,\r\n double prop, H1Comparition comp) {\r\n using namespace boost::math::quadrature;\r\n\r\n double z_cal = ((sampleProp - prop) / sqrt((prop * (1 - prop)) / sampleNumElements));\r\n\r\n auto f = [](const double &x) {\r\n double constant = 1 / sqrt(2 * M_PI);\r\n double e = exp(pow(x, 2));\r\n double sqrtE = 1 / sqrt(e);\r\n return constant * sqrtE;\r\n };\r\n\r\n double Q = gauss::integrate(f, -INFINITY, z_cal);\r\n\r\n double alpha = confidencelevel / 100;\r\n\r\n testHypothesisNull(comp, alpha, Q);\r\n return Q;\r\n}\r\n\r\n// This one is different from the rest, following \"Curso de estatistica.pdf\" on moodle,\r\n// we need to use chi square method to calculate p-value, so after some research we used\r\n// an implementation available online.\r\ndouble Hypothesis::testVariance(double sampleVar, unsigned long sampleNumElements, double confidencelevel,\r\n double var, H1Comparition comp) {\r\n using namespace boost::math::quadrature;\r\n\r\n int df = (int)sampleNumElements - 1;\r\n double chi_cal = (df * sampleVar) / var;\r\n\r\n double chi = ChiSquare(chi_cal, df);\r\n\r\n double alpha = confidencelevel / 100;\r\n\r\n double value_calc = 1 - chi;\r\n\r\n testHypothesisNull(comp, alpha, value_calc);\r\n return chi;\r\n}\r\n\r\n// Hypothesis test acording to p-value and confidence level and the type of comparation.\r\nvoid Hypothesis::testHypothesisNull(H1Comparition comp, double alpha, double value_calc){\r\n\r\n double value_critical = 1 - alpha;\r\n\r\n if (comp == H1Comparition::DIFFERENT) {\r\n\r\n double value_inf = alpha / 2;\r\n double value_sup = value_critical + value_inf;\r\n\r\n if (value_calc > value_sup or value_calc < value_inf) {\r\n printf(\"\\n # REJECT H0 => NOT EQUAL WITH %0.4f OF CONFIDENCE LEVEL\\n\\n\", alpha);\r\n } else {\r\n printf(\"\\n # ACCEPT H0 => EQUAL WITH %0.4f OF CONFIDENCE LEVEL\\n\\n\", alpha);\r\n }\r\n\r\n } else if (comp == H1Comparition::LESS_THAN) {\r\n\r\n if (value_calc < alpha) {\r\n printf(\"\\n # REJECT H0 => LESS THAN WITH %0.4f OF CONFIDENCE LEVEL\\n\\n\", alpha);\r\n } else {\r\n printf(\"\\n # ACCEPT H0 => NOT LESS THAN WITH %0.4f OF CONFIDENCE LEVEL\\n\\n\", alpha);\r\n }\r\n\r\n } else {\r\n\r\n if (value_calc > value_critical) {\r\n printf(\"\\n # REJECT H0 => GREATER THAN WITH %0.4f OF CONFIDENCE LEVEL\\n\\n\", alpha);\r\n } else {\r\n printf(\"\\n # ACCEPT H0 => NOT GREATER THAN WITH %0.4f OF CONFIDENCE LEVEL\\n\\n\", alpha);\r\n }\r\n\r\n }\r\n}\r\n\r\n// Reference: https://jamesmccaffrey.wordpress.com/2010/11/01/programmatically-computing-chi-square-critical-values\r\ndouble Hypothesis::ChiSquare(double x, int df) {\r\n // x = a computed chi-square value\r\n // df = degrees of freedom\r\n using namespace boost::math::quadrature;\r\n\r\n if (x <= 0.0 || df < 1) {\r\n printf(\"parameter x must be positive and parameter df must be 1 or greater\");\r\n };\r\n\r\n double a = 0; // 299 variable names\r\n double y = 0;\r\n double s = 0;\r\n double z = 0;\r\n double e = 0;\r\n double c;\r\n\r\n bool even; // is df even?\r\n\r\n a = 0.5 * x;\r\n if (df % 2 == 0) even = true; else even = false;\r\n\r\n if (df > 1) y = Exp(-a); // ACM update remark (4)\r\n\r\n auto f = [](const double &x) {\r\n double constant = 1 / sqrt(2 * M_PI);\r\n double ex = exp(pow(x, 2));\r\n double sqrtE = 1 / sqrt(ex);\r\n return constant * sqrtE;\r\n };\r\n\r\n if (even) s = y; else s = 2.0 * gauss::integrate(f, -INFINITY, -sqrt(x));\r\n\r\n if (df > 2)\r\n {\r\n x = 0.5 * (df - 1.0);\r\n if (even) z = 1.0; else z = 0.5;\r\n if (a > 40.0) // ACM remark (5)\r\n {\r\n if (even) e = 0.0; else e = 0.5723649429247000870717135; // log(sqrt(pi))\r\n c = log(a); // log base e\r\n while (z <= x)\r\n {\r\n e = log(z) + e;\r\n s = s + Exp(c * z - a - e); // ACM update remark (6)\r\n z = z + 1.0;\r\n }\r\n return s;\r\n } // a > 40.0\r\n else\r\n {\r\n if (even) e = 1.0; else e = 0.5641895835477562869480795 / sqrt(a); // (1 / sqrt(pi))\r\n c = 0.0;\r\n while (z <= x)\r\n {\r\n e = e * (a / z); // ACM update remark (7)\r\n c = c + e;\r\n z = z + 1.0;\r\n }\r\n return c * y + s;\r\n }\r\n }\r\n else\r\n {\r\n return s;\r\n }\r\n}\r\n\r\n// Reference: https://jamesmccaffrey.wordpress.com/2010/11/01/programmatically-computing-chi-square-critical-values/\r\ndouble Hypothesis::Exp(double x) { // ACM update remark (3)\r\n if (x < -40.0) // 40.0 is a magic number. ACM update remark (8)\r\n return 0.0;\r\n else\r\n return exp(x);\r\n}\r\n", "meta": {"hexsha": "a5aaae732a4f32fce807e2768983ad0c09373eca", "size": 6385, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hypothesis.cpp", "max_stars_repo_name": "Macelai/hypothesis-test", "max_stars_repo_head_hexsha": "22a18fbb586cbe293b764e4cbf8ed20a2e2a826b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hypothesis.cpp", "max_issues_repo_name": "Macelai/hypothesis-test", "max_issues_repo_head_hexsha": "22a18fbb586cbe293b764e4cbf8ed20a2e2a826b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hypothesis.cpp", "max_forks_repo_name": "Macelai/hypothesis-test", "max_forks_repo_head_hexsha": "22a18fbb586cbe293b764e4cbf8ed20a2e2a826b", "max_forks_repo_licenses": ["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.2552083333, "max_line_length": 117, "alphanum_fraction": 0.5705559906, "num_tokens": 1716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777987970316, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7781398302240837}} {"text": "#include \n#include \n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n cout.precision(3);\n MatrixXf m = MatrixXf::Random(3,2);\ncout << \"Here is the matrix m:\" << endl << m << endl;\nJacobiSVD svd(m, ComputeThinU | ComputeThinV);\ncout << \"Its singular values are:\" << endl << svd.singularValues() << endl;\ncout << \"Its left singular vectors are the columns of the thin U matrix:\" << endl << svd.matrixU() << endl;\ncout << \"Its right singular vectors are the columns of the thin V matrix:\" << endl << svd.matrixV() << endl;\nVector3f rhs(1, 0, 0);\ncout << \"Now consider this rhs vector:\" << endl << rhs << endl;\ncout << \"A least-squares solution of m*x = rhs is:\" << endl << svd.solve(rhs) << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "1b60a92a7c32d907fcf683b30e9f17bc1a6dcd81", "size": 834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_JacobiSVD_basic.cpp", "max_stars_repo_name": "shishaochen/TensorFlow-0.8-Win", "max_stars_repo_head_hexsha": "63221dfc4f1a1d064308e632ba12e6a54afe1fd8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-14T23:59:05.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-14T23:59:05.000Z", "max_issues_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_JacobiSVD_basic.cpp", "max_issues_repo_name": "shishaochen/TensorFlow-0.8-Win", "max_issues_repo_head_hexsha": "63221dfc4f1a1d064308e632ba12e6a54afe1fd8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-10-19T02:43:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-31T14:53:06.000Z", "max_forks_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_JacobiSVD_basic.cpp", "max_forks_repo_name": "shishaochen/TensorFlow-0.8-Win", "max_forks_repo_head_hexsha": "63221dfc4f1a1d064308e632ba12e6a54afe1fd8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2016-10-23T00:50:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-21T11:11:57.000Z", "avg_line_length": 30.8888888889, "max_line_length": 108, "alphanum_fraction": 0.6726618705, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217417, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7779662750534053}} {"text": "// Copyright Matthew Pulver 2018 - 2019.\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// https://www.boost.org/LICENSE_1_0.txt)\n\n#include \n#include \n\ntemplate\nT fourth_power(T x)\n{\n x *= x;\n return x *= x;\n}\n\nint main()\n{\n using namespace boost::math::differentiation;\n\n constexpr int Order=5; // The highest order derivative to be calculated.\n const autodiff_fvar x = make_fvar(2.0); // Find derivatives at x=2.\n const autodiff_fvar y = fourth_power(x);\n for (int i=0 ; i<=Order ; ++i)\n std::cout << \"y.derivative(\"<\n#include \n\n#include \n\n#include \n#include \n\nclass NatCSI {\npublic:\n NatCSI(const std::vector & t, const std::vector & y)\n : t(t), y(y), h(t.size()-1), c(t.size()) {\n // Size check\n assert( ( t.size() == y.size() ) && \"Error: mismatched size of t and y!\");\n \n // m is the number of conditions (t goes from t_0 to t_n)\n // WARNING: m = n+1\n m = t.size();\n \n // Vector containing increments (from the right)\n for(int i = 0; i < (m - 1); ++i) {\n h(i) = t[i+1] - t[i];\n // Check that t is sorted\n assert( ( h(i) > 0 ) && \"Error: array t must be sorted!\");\n }\n \n // System matrix and rhs as in 3.5.9, we remove first and last row (known by natural contition)\n Eigen::SparseMatrix A(m,m);\n Eigen::VectorXd b(m);\n \n // WARNING: sparse reserve space\n A.reserve(3);\n \n // Fill in natural conditions 3.5.10 for matrix\n A.coeffRef(0,0) = 2 / h(0);\n A.coeffRef(0,1) = 1 / h(0);\n A.coeffRef(m-1,m-2) = 1 / h(m-2);\n A.coeffRef(m-1,m-1) = 2 / h(m-2);\n \n // Reuse computation for rhs\n double bold = (y[1] - y[0]) / (h(0)*h(0));\n b(0) = 3*bold; // Fill in natural conditions 3.5.10\n // Fill matrix A and rhs b\n for(int i = 1; i < m-1; ++i) {\n // PRecompute b_i\n double hinv = 1./h(i);\n \n // Fill in a\n A.coeffRef(i,i-1) = hinv;\n A.coeffRef(i,i) = 2./h(i) + 2./h(i-1);\n A.coeffRef(i,i+1) = hinv;\n \n // Reuse computation for rhs b\n double bnew = (y[i+1] - y[i]) / (h(i)*h(i));\n b(i) = 3. * (bnew + bold);\n bold = bnew;\n }\n b(m-1) = 3*bold; // Fill in natural conditions 3.5.10\n // Compress the matrix\n A.makeCompressed();\n std::cout << A;\n \n // Factorize A and solve system A*c(1:end) = b\n Eigen::SparseLU> lu;\n lu.compute(A);\n c = lu.solve(b);\n \n }\n \n double operator() (double x) const {\n // Assert that x \\in (t_0, t_n)\n assert( ( t[0] <= x && x <= t[m-1] ) && \"Error: x must be in (t_0, t_n)\");\n \n // Find j s.t. x \\in (t_j,t_j+1)\n // as with the previous sheet (PS 6), we perform an efficient binary search on the data (log. complexity)\n auto j = (std::lower_bound(t.begin(), t.end(), x) - t.begin()) - 1;\n if( j == -1 ) j++;\n \n \n // Precompute tau and evaluate spline (3.5.5)\n double tau = (x - t[j]) / h(j);\n double tau2 = tau*tau;\n double tau3 = tau2*tau;\n return y[j] * ( 1. - 3. * tau2 + 2 * tau3 ) +\n y[j+1] * ( 3 * tau2 - 2 * tau3 ) +\n h(j) * c(j) * ( tau - 2 * tau2 + tau3 ) +\n h(j) * c(j+1) * ( - tau2 + tau3 );\n \n }\n \nprivate:\n // Provided nodes and values to compute spline, same size Eigen vectors\n std::vector t, y;\n // Difference t(i)-t(i-1) and coefficients of spline (s'(t_j))\n Eigen::VectorXd h, c;\n // Size of t, y and c = m. h has size m-1\n int m;\n};\n\nint main() {\n \n int n = 8, m = 100;\n std::vector t;\n std::vector y;\n t.resize(n);\n y.resize(n);\n for(int i = 0; i < n; ++i) {\n t[i] = (double) i / (n-1);\n y[i] = cos(t[i]);\n }\n \n NatCSI N(t,y);\n \n Eigen::VectorXd x = Eigen::VectorXd::LinSpaced(m, 0, 1);\n for(int i = 0; i < x.size(); ++i) {\n x(i) = N(x(i));\n }\n std::cout << x << std::endl;\n}\n", "meta": {"hexsha": "3f5a69f697560c4e2d7210582ef241290a9b1b04", "size": 3769, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS8/solutions_ps8/natcsi.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS8/solutions_ps8/natcsi.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS8/solutions_ps8/natcsi.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4083333333, "max_line_length": 113, "alphanum_fraction": 0.4582117272, "num_tokens": 1189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7774067544034194}} {"text": "#include \n#include \n\nvoid gramSchmidtOrthogonalization(Eigen::MatrixXd &matrix,Eigen::MatrixXd &orthonormalMatrix)\n{\n/*\n In this method you make every column perpendicular to it's previous columns,\n here if a and b are representation vector of two columns, c=b-((b.a)/|a|).a\n ^\n /\n b /\n /\n /\n ---------->\n a\n ^\n /|\n b / |\n / | c\n / |\n ---------->\n a\n you just have to normilze every vector after make it perpendicular to previous columns\n so:\n q1=a.normalized();\n q2=b-(b.q1).q1\n q2=q2.normalized();\n q3=c-(c.q1).q1 - (c.q2).q2\n q3=q3.normalized();\n Now we have Q, but we want A=QR so we just multiply both side by Q.transpose(), since Q is orthonormal, Q*Q.transpose() is I\n A=QR;\n Q.transpose()*A=R;\n*/\n Eigen::VectorXd col;\n for(int i=0;i qr(A);\n q = qr.householderQ();\n thinQ.setIdentity();\n thinQ = qr.householderQ() * thinQ;\n std::cout << \"Q computed by Eigen\" << \"\\n\\n\" << thinQ << \"\\n\\n\";\n std::cout << q << \"\\n\\n\" << thinQ << \"\\n\\n\";\n\n\n}\n\nvoid gramSchmidtOrthogonalizationExample()\n{\n Eigen::MatrixXd matrix(3,4),orthonormalMatrix(3,4) ;\n matrix=Eigen::MatrixXd::Random(3,4);////A.setRandom();\n\n\n gramSchmidtOrthogonalization(matrix,orthonormalMatrix);\n}\n\n\n\nint main()\n{\n\n}\n", "meta": {"hexsha": "4827f06fe844f4826a12fe584c7c179c64f364b5", "size": 2541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gram_schmidt_orthogonalization.cpp", "max_stars_repo_name": "behnamasadi/Mastering_Eigen", "max_stars_repo_head_hexsha": "99edbc819c89a4805b777eef69044a1658d96206", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-04-14T16:54:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T15:55:08.000Z", "max_issues_repo_path": "src/gram_schmidt_orthogonalization.cpp", "max_issues_repo_name": "behnamasadi/Mastering_Eigen", "max_issues_repo_head_hexsha": "99edbc819c89a4805b777eef69044a1658d96206", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gram_schmidt_orthogonalization.cpp", "max_forks_repo_name": "behnamasadi/Mastering_Eigen", "max_forks_repo_head_hexsha": "99edbc819c89a4805b777eef69044a1658d96206", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-25T10:08:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-06T14:27:32.000Z", "avg_line_length": 22.0956521739, "max_line_length": 128, "alphanum_fraction": 0.5521448249, "num_tokens": 839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7774067476188545}} {"text": "//\n// Created by jhwangbo on 23.09.16.\n// This function is to solve linear equation Ax=b\n\n#ifndef RAI_CONJUGATEGRADIENT_HPP\n#define RAI_CONJUGATEGRADIENT_HPP\n#include \n#include \n#include \n\nnamespace rai{\n//namespace Math{\n\ntemplate \nDerived conjugateGradient(std::function< void(Eigen::Matrix&,\n Eigen::Matrix&)> eval,\n Eigen::Matrix b,\n int iterN, Derived tol, Eigen::Matrix& sol)\n{\n int dim = b.rows();\n Eigen::Matrix x, p, r, Ap, Ar, pnew, Apnew;\n x.setZero(dim); Ap.setZero(dim); Ar.setZero(dim); pnew.setZero(dim);\n r = b;\n p = b;\n\n Derived rdotr = r.squaredNorm();\n Derived newrdotr=0;\n int i;\n for(i = 0; i < iterN && i < dim; i++){\n eval(p, Ap);\n Derived a = rdotr / p.dot(Ap);\n x += a * p;\n r -= a * Ap;\n newrdotr = r.dot(r);\n if (newrdotr < tol)\n break;\n Derived b = newrdotr/rdotr;\n p = r + b * p;\n rdotr = newrdotr;\n }\n sol = x;\n return newrdotr;\n};\n\n}\n//}\n\n#endif //RAI_CONJUGATEGRADIENT_HPP\n", "meta": {"hexsha": "782ba6bf5ffa7ba98d080de9514b0908d5a16c41", "size": 1167, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/raiCommon/math/ConjugateGradient.hpp", "max_stars_repo_name": "Wistral/raicommon", "max_stars_repo_head_hexsha": "f6f3623bfa3a80a9ede4e79afc37195af3fb8609", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/raiCommon/math/ConjugateGradient.hpp", "max_issues_repo_name": "Wistral/raicommon", "max_issues_repo_head_hexsha": "f6f3623bfa3a80a9ede4e79afc37195af3fb8609", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/raiCommon/math/ConjugateGradient.hpp", "max_forks_repo_name": "Wistral/raicommon", "max_forks_repo_head_hexsha": "f6f3623bfa3a80a9ede4e79afc37195af3fb8609", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-05-05T20:33:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T07:47:53.000Z", "avg_line_length": 23.8163265306, "max_line_length": 82, "alphanum_fraction": 0.5792630677, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133481428691, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7770374442947768}} {"text": "#include \n#include \n\nusing namespace std;\nusing namespace Eigen;\n\nint main()\n{\n VectorXf v(2);\n MatrixXf m(2,2), n(2,2);\n \n v << -1,\n 2;\n \n m << 1,-2,\n -3,4;\n\n cout << \"v.squaredNorm() = \" << v.squaredNorm() << endl;\n cout << \"v.norm() = \" << v.norm() << endl;\n cout << \"v.lpNorm<1>() = \" << v.lpNorm<1>() << endl;\n cout << \"v.lpNorm() = \" << v.lpNorm() << endl;\n\n cout << endl;\n cout << \"m.squaredNorm() = \" << m.squaredNorm() << endl;\n cout << \"m.norm() = \" << m.norm() << endl;\n cout << \"m.lpNorm<1>() = \" << m.lpNorm<1>() << endl;\n cout << \"m.lpNorm() = \" << m.lpNorm() << endl;\n}\n", "meta": {"hexsha": "740439fb37c70054144476197ef892e4a40fd00d", "size": 675, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/doc/examples/Tutorial_ReductionsVisitorsBroadcasting_reductions_norm.cpp", "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3457.0, "max_stars_repo_stars_event_min_datetime": "2018-06-09T15:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T22:09:25.000Z", "max_issues_repo_path": "src/Eigen-3.3/doc/examples/Tutorial_ReductionsVisitorsBroadcasting_reductions_norm.cpp", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "src/Eigen-3.3/doc/examples/Tutorial_ReductionsVisitorsBroadcasting_reductions_norm.cpp", "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1380.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "avg_line_length": 23.275862069, "max_line_length": 68, "alphanum_fraction": 0.5022222222, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7769814161464731}} {"text": "#include \n\n#include \n#include \n\n#include \n\n//! \\brief One step of autonomous IVP y'' + y' + y = 0, [y(0), y'(0)] = z0 using SDIRK method\n//! Use SDIRK method for first order ode z' = f(z). Steps of size h.\n//! \\tparam StateType type of solution space y and initial data y0\n//! \\param[in] z0 initial data z(0)\n//! \\param[in] h size of the step\n//! \\param[in] gamma parameter\n//! \\return next step z1\ntemplate \nStateType sdirkStep(const StateType & z0, double h, double gamma) {\n // Matrix A for evaluation of f\n Eigen::Matrix2d A;\n A << 0.,1.,-1.,-1.;\n \n // Reuse factorization\n auto A_lu = (Eigen::Matrix2d::Identity()-h*gamma*A).partialPivLu();\n Eigen::Vector2d az = A*z0;\n \n // Increments\n Eigen::Vector2d k1 = A_lu.solve(az);\n Eigen::Vector2d k2 = A_lu.solve(az + h*(1-2*gamma)*A*k1);\n \n // Next step\n return z0 + h*0.5*(k1 + k2);\n}\n\n//! \\brief Solve autonomous IVP y'' + y' + y = 0, [y(0), y'(0)] = z0 using SDIRK method\n//! Use SDIRK method for first order ode z' = f(z), with N equidistant steps\n//! \\tparam StateType type of solution space z = [y,y']! and initial data z0 = [y(0), y'(0)]\n//! \\param[in] z0 initial data z(0)\n//! \\param[in] N number of equidistant steps\n//! \\param[in] T final time of simulation\n//! \\param[in] gamma parameter\n//! \\return vector containing each step of z_k (y and y')\ntemplate \nstd::vector sdirkSolve(const StateType & z0, unsigned int N, double T, double gamma) {\n // Solution vector\n std::vector res(N+1);\n // Equidistant step size\n const double h = T/N;\n \n // Push initial data\n res.at(0) = z0;\n \n // Main loop\n for(unsigned int i = 1; i <= N; ++i) {\n res.at(i) = sdirkStep(res.at(i-1), h, gamma);\n }\n \n return res;\n}\n\nint main() {\n // Initial data z0 = [y(0), y'(0)]\n Eigen::Vector2d z0;\n z0 << 1,0;\n // Final time\n const double T = 10;\n // Parameter \n const double gamma = (3.+std::sqrt(3.)) / 6.;\n // Mesh sizes\n std::vector N = {20, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240};\n // Exact solution (only y(t)) given z0 = [y(0), y'(0)] and t\n auto yex = [&z0] (double t) {\n return 1./3.*std::exp(-t/2.) * ( 3.*z0(0) * std::cos( std::sqrt(3.)*t/2. ) + \n std::sqrt(3.)*z0(0) * std::sin( std::sqrt(3.)*t/2. ) + \n 2.*std::sqrt(3.)*z0(1) * std::sin( std::sqrt(3.)*t/2. ) );\n };\n \n // Store old error for rate computation\n double errold = 0;\n std::cout << std::setw(15) << \"n\" << std::setw(15) << \"maxerr\" << std::setw(15) << \"rate\" << std::endl;\n // Loop over all meshes\n for(unsigned int i = 0; i < N.size(); ++i) {\n int n = N.at(i);\n // Get solution\n auto sol = sdirkSolve(z0, n, T, gamma);\n // Compute error\n double err = std::abs(sol.back()(0) - yex(T));\n \n // I/O\n std::cout << std::setw(15) << n << std::setw(15) << err;\n if(i > 0) std::cout << std::setw(15) << std::log2(errold /err);\n std::cout << std::endl;\n \n // Store old error\n errold = err;\n }\n}\n", "meta": {"hexsha": "67cd38053c8305cacf6016b1184626d00aa1151b", "size": 3160, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS14/solutions_ps14/sdirk.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS14/solutions_ps14/sdirk.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS14/solutions_ps14/sdirk.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9166666667, "max_line_length": 107, "alphanum_fraction": 0.5566455696, "num_tokens": 1089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672954, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.7769811976403701}} {"text": "//\n// Created by Harold on 2021/4/11.\n//\n\n#ifndef M_MATH_M_FFT_EIGEN_HPP\n#define M_MATH_M_FFT_EIGEN_HPP\n\n#include \n#include \n#include \n\n#ifdef _OPENMP\n#include \n#endif\n\n#include \"m_circshift_eigen.hpp\"\n\nnamespace M_MATH {\n // 2D fft, requires fft shift\n template\n Eigen::Matrix, Eigen::Dynamic, Eigen::Dynamic>\n ForwardFFT(Eigen::MatrixBase const& mat) {\n auto rows = mat.rows();\n auto cols = mat.cols();\n Eigen::FFT fft;\n Eigen::Matrix, Eigen::Dynamic, Eigen::Dynamic> res(rows, cols);\n // need apply 1d fft on both rows and cols\n for (auto i = 0; i < rows; ++i) {\n Eigen::Matrix, Eigen::Dynamic, 1> tmp(cols);\n fft.fwd(tmp, mat.row(i).eval());\n res.row(i) = tmp;\n }\n for (auto i = 0; i < cols; ++i) {\n Eigen::Matrix, 1, Eigen::Dynamic> tmp(rows);\n fft.fwd(tmp, res.col(i).eval());\n res.col(i) = tmp;\n }\n return res;\n }\n\n // 2D ifft, requires fft shift\n template\n Eigen::Matrix\n BackwardFFT(Eigen::Matrix, Eigen::Dynamic, Eigen::Dynamic> const& mat) {\n auto rows = mat.rows();\n auto cols = mat.cols();\n Eigen::FFT fft;\n Eigen::Matrix, Eigen::Dynamic, Eigen::Dynamic> tmpMat(rows, cols);\n Eigen::Matrix res(rows, cols);\n // need apply 1d fft on both rows and cols\n for (auto i = 0; i < rows; ++i) {\n Eigen::Matrix, Eigen::Dynamic, 1> tmp(cols);\n fft.inv(tmp, mat.row(i).eval());\n tmpMat.row(i) = tmp;\n }\n for (auto i = 0; i < cols; ++i) {\n Eigen::Matrix, 1, Eigen::Dynamic> tmp(rows);\n fft.inv(tmp, tmpMat.col(i).eval());\n res.col(i) = tmp.real();\n }\n return res;\n }\n\n // OMP one is slower according to benchmark result (see bench/fft_bench.cpp)\n template\n Eigen::Matrix, Eigen::Dynamic, Eigen::Dynamic>\n ForwardFFT_OMP(Eigen::MatrixBase const& mat) {\n auto rows = mat.rows();\n auto cols = mat.cols();\n Eigen::FFT fft;\n Eigen::Matrix, Eigen::Dynamic, Eigen::Dynamic> res(rows, cols);\n // need apply 1d fft on both rows and cols\n#pragma omp parallel sections\n {\n#pragma omp section\n {\n#pragma omp parallel for if (rows > 10) schedule(static)\n for (auto i = 0; i < rows; ++i) {\n Eigen::Matrix, Eigen::Dynamic, 1> tmp(cols);\n fft.fwd(tmp, mat.row(i).eval());\n res.row(i) = tmp;\n }\n#pragma omp parallel for if (cols > 10) schedule(static)\n for (auto i = 0; i < cols; ++i) {\n Eigen::Matrix, 1, Eigen::Dynamic> tmp(rows);\n fft.fwd(tmp, res.col(i).eval());\n res.col(i) = tmp;\n }\n }\n }\n return res;\n }\n\n template \n Eigen::CircShiftedView circShift(Eigen::DenseBase& x, RowShift r, ColShift c)\n {\n return Eigen::CircShiftedView(x.derived(), r, c);\n }\n\n template \n Eigen::CircShiftedView fftshift(Eigen::DenseBase& x)\n {\n Eigen::Index rs = x.rows() / 2;\n Eigen::Index cs = x.cols() / 2;\n return Eigen::CircShiftedView(x.derived(), rs, cs);\n }\n\n template \n Eigen::CircShiftedView ifftshift(Eigen::DenseBase& x)\n {\n Eigen::Index rs = (x.rows() + 1) / 2;\n Eigen::Index cs = (x.cols() + 1) / 2;\n return Eigen::CircShiftedView(x.derived(), rs, cs);\n }\n}\n\n#endif //M_MATH_M_FFT_EIGEN_HPP\n", "meta": {"hexsha": "a1afe5d05972817b386d902019dfea1938b98058", "size": 4524, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/m_fft_eigen.hpp", "max_stars_repo_name": "Harold2017/m_math", "max_stars_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-04T12:26:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T08:00:15.000Z", "max_issues_repo_path": "include/m_fft_eigen.hpp", "max_issues_repo_name": "Harold2017/m_math", "max_issues_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-03T02:50:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T06:32:29.000Z", "max_forks_repo_path": "include/m_fft_eigen.hpp", "max_forks_repo_name": "Harold2017/m_math", "max_forks_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-04T12:26:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-04T12:26:12.000Z", "avg_line_length": 38.3389830508, "max_line_length": 119, "alphanum_fraction": 0.5875331565, "num_tokens": 1200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799420543365, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7764521489111487}} {"text": "#pragma once\n#include \n\nnamespace mtao::linear_algebra {\n // the gram schmidt algorithm with a threshold for when 0-eigenvalues are found\n template \n void gram_schmidt_in_place(Eigen::PlainObjectBase& M) {\n using Scalar = typename Derived::Scalar;\n constexpr Scalar eps = std::numeric_limits::epsilon();\n for(int j = 0; j < M.cols(); ++j) {\n auto u = M.col(j);\n Scalar n = u.squaredNorm();\n for(int k = 0; k < j; ++k) {\n auto v = M.col(k);\n u -= v.dot(u) * v;\n }\n if(u.squaredNorm() < eps * n) {\n u.setZero();\n } else {\n u.normalize();\n }\n }\n }\n template \n auto gram_schmidt(const Eigen::MatrixBase& M) {\n typename Derived::PlainMatrix O = M;\n gram_schmidt_in_place(O);\n return O;\n }\n}\n", "meta": {"hexsha": "b837db3d590ec7996c3fd9c144ae5626d7a4e688", "size": 1055, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/linear_algebra/gram_schmidt.hpp", "max_stars_repo_name": "mtao/core", "max_stars_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/mtao/linear_algebra/gram_schmidt.hpp", "max_issues_repo_name": "mtao/core", "max_issues_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:17:36.000Z", "max_forks_repo_path": "include/mtao/linear_algebra/gram_schmidt.hpp", "max_forks_repo_name": "mtao/core", "max_forks_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0322580645, "max_line_length": 83, "alphanum_fraction": 0.482464455, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693645535724, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7764254396138305}} {"text": "#pragma once\r\n\r\n#include \t\t// For console i/o\r\n#include \t\t// For vectors, not including linear algebra\r\n#include \t\t// For random number generation\r\n#include \t// For min/max functions\r\n\r\n// Additional libraries that you will have to download.\r\n// First is Eigen, which we use for linear algebra: http://eigen.tuxfamily.org/index.php?title=Main_Page\r\n#include \r\n// Second is Boost, which we use for ibeta_inv: https://www.boost.org/\r\n#include \r\n\r\n// Typically these shouldn't be in a .hpp file.\r\nusing namespace std;\r\nusing namespace Eigen;\r\nusing namespace boost::math;\r\n\r\n// This function returns the inverse of Student's t CDF using the degrees of\r\n// freedom in nu for the corresponding probabilities in p. That is, it is\r\n// a C++ implementation of Matlab's tinv function: https://www.mathworks.com/help/stats/tinv.html\r\n// To see how this was created, see the \"quantile\" block here: https://www.boost.org/doc/libs/1_58_0/libs/math/doc/html/math_toolkit/dist_ref/dists/students_t_dist.html\r\ndouble tinv(double p, unsigned int nu) {\r\n\tdouble x = ibeta_inv((double)nu / 2.0, 0.5, 2.0 * min(p, 1.0 - p));\r\n\treturn sign(p - 0.5) * sqrt((double)nu * (1.0 - x) / x);\r\n}\r\n\r\n// Get the sample standard deviation of the vector v (an Eigen::VectorXd)\r\ndouble stddev(const VectorXd& v) {\r\n\tdouble mu = v.mean(), result = 0;\t\t\t// Get the sample mean\r\n\tfor (unsigned int i = 0; i < v.size(); i++)\r\n\t\tresult += (v[i] - mu) * (v[i] - mu);\t// Compute the sum of the squared differences between samples and the sample mean\r\n\tresult = sqrt(result / (v.size() - 1.0));\t// Get the sample variance by dividing by the number of samples minus one, and then the sample standard deviation by taking the square root.\r\n\treturn result;\t\t\t\t\t\t\t\t// Return the value that we've computed.\r\n}\r\n\r\n// Assuming v holds i.i.d. samples of a random variable, compute\r\n// a (1-delta)-confidence upper bound on the expected value of the random\r\n// variable using Student's t-test. That is:\r\n// sampleMean + sampleStandardDeviation/sqrt(n) * tinv(1-delta, n-1),\r\n// where n is the number of points in v.\r\n//\r\n// If numPoints is provided, then ttestUpperBound predicts what its output would be if it were to\r\n// be run using a new vector, v, containing numPoints values sampled from the same distribution as\r\n// the points in v.\r\ndouble ttestUpperBound(const VectorXd& v, const double& delta, const int numPoints = -1) {\r\n\tunsigned int n = (numPoints == -1 ? (unsigned int)v.size() : (unsigned int)numPoints);\t// Set n to be numPoints if it was provided, and the number of points in v otherwise.\r\n\treturn v.mean() + (numPoints != -1 ? 2.0 : 1.0) * stddev(v) / sqrt((double)n) * tinv(1.0 - delta, n - 1u);\r\n}\r\n\r\ndouble ttestLowerBound(const VectorXd& v, const double& delta, const int numPoints = -1) {\r\n unsigned int n = (numPoints == -1 ? (unsigned int)v.size() : (unsigned int)numPoints);\t// Set n to be numPoints if it was provided, and the number of points in v otherwise.\r\n return v.mean() - (numPoints != -1 ? 2.0 : 1.0) * stddev(v) / sqrt((double)n) * tinv(1.0 - delta, n - 1u);\r\n}\r\n\r\n/*\r\nThis function implements CMA-ES (http://en.wikipedia.org/wiki/CMA-ES). Return\r\nvalue is the minimizer / maximizer. This code is written for brevity, not clarity.\r\nSee the link above for a description of what this code is doing.\r\n*/\r\nVectorXd CMAES(\r\n\tconst VectorXd& initialMean,\t\t\t\t\t\t\t\t\t\t\t// Starting point of the search\r\n\tconst double& initialSigma,\t\t\t\t\t\t\t\t\t\t\t\t// Initial standard deviation of the search around initialMean\r\n\tconst unsigned int& numIterations,\t\t\t\t\t\t\t\t\t\t// Number of iterations to run before stopping\r\n\t// f, below, is the function to be optimized. Its first argument is the solution, the middle arguments are variables required by f (listed below), and the last is a random number generator.\r\n\tdouble(*f)(const VectorXd& theta, const void* params[], mt19937_64& generator),\r\n\tconst void* params[],\t\t\t\t\t\t\t\t\t\t\t\t\t// Parrameters of f other than theta\r\n\tconst bool& minimize,\t\t\t\t\t\t\t\t\t\t\t\t\t// If true, we will try to minimize f. Otherwise we will try to maximize f\r\n\tmt19937_64& generator)\t\t\t\t\t\t\t\t\t\t\t\t\t// The random number generator to use\r\n{\r\n\t// Define all of the terms that we will use in the iterations\r\n\tunsigned int N = (unsigned int)initialMean.size(), lambda = 4 + (unsigned int)floor(3.0 * log(N)), hsig;\r\n\tdouble sigma = initialSigma, mu = lambda / 2.0, eigeneval = 0, chiN = pow(N, 0.5) * (1.0 - 1.0 / (4.0 * N) + 1.0 / (21.0 * N * N));\r\n\tVectorXd xmean = initialMean, weights((unsigned int)mu);\r\n\tfor (unsigned int i = 0; i < (unsigned int)mu; i++)\r\n\t\tweights[i] = i + 1;\r\n\tweights = log(mu + 1.0 / 2.0) - weights.array().log();\r\n\tmu = floor(mu);\r\n\tweights = weights / weights.sum();\r\n\tdouble mueff = weights.sum() * weights.sum() / weights.dot(weights), cc = (4.0 + mueff / N) / (N + 4.0 + 2.0 * mueff / N), cs = (mueff + 2.0) / (N + mueff + 5.0), c1 = 2.0 / ((N + 1.3) * (N + 1.3) + mueff), cmu = min(1.0 - c1, 2.0 * (mueff - 2.0 + 1.0 / mueff) / ((N + 2.0) * (N + 2.0) + mueff)), damps = 1.0 + 2.0 * max(0.0, sqrt((mueff - 1.0) / (N + 1.0)) - 1.0) + cs;\r\n\tVectorXd pc = VectorXd::Zero(N), ps = VectorXd::Zero(N), D = VectorXd::Ones(N), DSquared = D, DInv = 1.0 / D.array(), xold, oneOverD;\r\n\tfor (unsigned int i = 0; i < DSquared.size(); i++)\r\n\t\tDSquared[i] *= DSquared[i];\r\n\tMatrixXd B = MatrixXd::Identity(N, N), C = B * DSquared.asDiagonal() * B.transpose(), invsqrtC = B * DInv.asDiagonal() * B.transpose(), arx(N, (int)lambda), repmat(xmean.size(), (int)(mu + .1)), artmp, arxSubMatrix(N, (int)(mu + .1));\r\n\tvector arfitness(lambda);\r\n\tvector arindex(lambda);\r\n\t// Perform the iterations\r\n\tfor (unsigned int counteval = 0; counteval < numIterations;) {\r\n\t cout << \"Sampling Population\" << endl;\r\n\t\t// Sample the population\r\n\t\tfor (unsigned int k = 0; k < lambda; k++) {\r\n\t\t\tnormal_distribution distribution(0, 1);\r\n\t\t\tVectorXd randomVector(N);\r\n\t\t\tfor (unsigned int i = 0; i < N; i++)\r\n\t\t\t\trandomVector[i] = D[i] * distribution(generator);\r\n\t\t\tarx.col(k) = xmean + sigma * B * randomVector;\r\n \t\t}\r\n\t\t// Evaluate the population\r\n\t\tvector fInputs(lambda);\r\n\t\tfor (unsigned int i = 0; i < lambda; i++) {\r\n\t\t cout << \"Evaluating Candidate \" << counteval+i << \"/\" << numIterations << endl;\r\n\t\t\tfInputs[i] = arx.col(i);\r\n cout << \"Theta: \" << fInputs[i].transpose() << endl;\r\n\t\t\tarfitness[i] = (minimize ? 1 : -1) * f(fInputs[i], params, generator);\r\n\t\t}\r\n\t\t// Update the population distribution\r\n\t\tcounteval += lambda;\r\n\t\txold = xmean;\r\n\t\tfor (unsigned int i = 0; i < lambda; ++i)\r\n\t\t\tarindex[i] = i;\r\n\t\tstd::sort(arindex.begin(), arindex.end(), [&arfitness](unsigned int i1, unsigned int i2) {return arfitness[i1] < arfitness[i2]; });\r\n\t\tfor (unsigned int col = 0; col < (unsigned int)mu; col++)\r\n\t\t\tarxSubMatrix.col(col) = arx.col(arindex[col]);\r\n\t\txmean = arxSubMatrix * weights;\r\n\t\tps = (1.0 - cs) * ps + sqrt(cs * (2.0 - cs) * mueff) * invsqrtC * (xmean - xold) / sigma;\r\n\t\thsig = (ps.norm() / sqrt(1.0 - pow(1.0 - cs, 2.0 * counteval / lambda)) / (double)chiN < 1.4 + 2.0 / (N + 1.0) ? 1 : 0);\r\n\t\tpc = (1 - cc) * pc + hsig * sqrt(cc * (2 - cc) * mueff) * (xmean - xold) / sigma;\r\n\t\tfor (unsigned int i = 0; i < repmat.cols(); i++)\r\n\t\t\trepmat.col(i) = xold;\r\n\t\tartmp = (1.0 / sigma) * (arxSubMatrix - repmat);\r\n\t\tC = (1 - c1 - cmu) * C + c1 * (pc * pc.transpose() + (1u - hsig) * cc * (2 - cc) * C) + cmu * artmp * weights.asDiagonal() * artmp.transpose();\r\n\t\tsigma = sigma * exp((cs / damps) * (ps.norm() / (double)chiN - 1.0));\r\n\t\tif ((double)counteval - eigeneval > (double)lambda / (c1 + cmu) / (double)N / 10.0) {\r\n\t\t\teigeneval = counteval;\r\n\t\t\tfor (unsigned int r = 0; r < C.rows(); r++)\r\n\t\t\t\tfor (unsigned int c = r + 1; c < C.cols(); c++)\r\n\t\t\t\t\tC(r, c) = C(c, r);\r\n\t\t\tEigenSolver es(C);\r\n\t\t\tD = C.eigenvalues().real();\r\n\t\t\tB = es.eigenvectors().real();\r\n\t\t\tD = D.array().sqrt();\r\n\t\t\tfor (unsigned int i = 0; i < B.cols(); i++)\r\n\t\t\t\tB.col(i) = B.col(i).normalized();\r\n\t\t\toneOverD = 1.0 / D.array();\r\n\t\t\tinvsqrtC = B * oneOverD.asDiagonal() * B.transpose();\r\n\t\t}\r\n\t} // End loop over iterations\r\n\treturn arx.col(arindex[0]);\r\n}", "meta": {"hexsha": "92944939250c28298b5f6815e0ada8e39adcf980", "size": 8198, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Project/headers/HelperFunctions.hh", "max_stars_repo_name": "anshuman1811/cs687-reinforcementlearning", "max_stars_repo_head_hexsha": "cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Project/headers/HelperFunctions.hh", "max_issues_repo_name": "anshuman1811/cs687-reinforcementlearning", "max_issues_repo_head_hexsha": "cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Project/headers/HelperFunctions.hh", "max_forks_repo_name": "anshuman1811/cs687-reinforcementlearning", "max_forks_repo_head_hexsha": "cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 58.9784172662, "max_line_length": 372, "alphanum_fraction": 0.6330812393, "num_tokens": 2540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630937, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7763580028989948}} {"text": "/* This sample is based on the Chapter 1 from book\n * \"Building Machine Learning Systems with Python\" by Willi Richert\n */\n\n// third party includes\n#include \n#include \n#include \n\n// stl includes\n#include \n#include \n#include \n#include \n#include \n\n// application includes\n#include \"../ioutils.h\"\n#include \"../utils.h\"\n\n// Namespace and type aliases\nnamespace fs = std::experimental::filesystem;\ntypedef double DType;\nusing Matrix = Eigen::Matrix;\n\nauto standardize(const Matrix& v) {\n assert(v.cols() == 1);\n auto m = v.colwise().mean();\n auto n = v.rows();\n DType sd = std::sqrt((v.rowwise() - m).array().pow(2).sum() /\n static_cast(n - 1));\n Matrix sv = (v.rowwise() - m) / sd;\n return std::make_tuple(sv, m(0, 0), sd);\n}\n\nauto generate_polynomial(const Matrix& x, size_t degree) {\n assert(x.cols() == 1);\n auto rows = x.rows();\n\n Matrix poly_x = Matrix::Zero(rows, degree);\n // fill additional column for simpler vectorization\n {\n auto xv = poly_x.block(0, 0, rows, 1);\n xv.setOnes();\n }\n // copy initial data\n {\n auto xv = poly_x.block(0, 1, rows, 1);\n xv = x;\n }\n // generate additional terms\n for (size_t i = 2; i < degree; ++i) {\n auto xv = poly_x.block(0, i, rows, 1);\n xv = x.array().pow(static_cast(i));\n }\n return poly_x;\n}\n\nauto bgd(const Matrix& x, const Matrix& y) {\n size_t batch_size = 8;\n size_t n_epochs = 1000;\n DType lr = 0.0015;\n\n auto rows = x.rows();\n auto cols = x.cols();\n\n size_t batches = rows / batch_size; // some samples will be skipped\n Matrix b = Matrix::Zero(cols, 1);\n\n DType prev_cost = std::numeric_limits::max();\n for (size_t i = 0; i < n_epochs; ++i) {\n for (size_t bi = 0; bi < batches; ++bi) {\n auto s = bi * batch_size;\n auto batch_x = x.block(s, 0, batch_size, cols);\n auto batch_y = y.block(s, 0, batch_size, 1);\n\n auto yhat = batch_x * b;\n auto error = yhat - batch_y;\n\n auto grad =\n (batch_x.transpose() * error) / static_cast(batch_size);\n\n b = b - lr * grad;\n }\n\n DType cost = (y - x * b).array().pow(2.f).sum() / static_cast(rows);\n\n std::cout << \"BGD iteration : \" << i << \" Cost = \" << cost << std::endl;\n if (cost <= prev_cost)\n prev_cost = cost;\n else\n break; // early stopping\n }\n return b;\n}\n\nint main() {\n // Download the data\n const std::string data_path{\"web_traffic.tsv\"};\n if (!fs::exists(data_path)) {\n const std::string data_url{\n R\"(https://raw.githubusercontent.com/luispedro/BuildingMachineLearningSystemsWithPython/master/ch01/data/web_traffic.tsv)\"};\n if (!utils::DownloadFile(data_url, data_path)) {\n std::cerr << \"Unable to download the file \" << data_url << std::endl;\n return 1;\n }\n }\n\n // Read the data\n io::CSVReader<2, io::trim_chars<' '>, io::no_quote_escape<'\\t'>> data_tsv(\n data_path);\n\n std::vector raw_data_x;\n std::vector raw_data_y;\n\n bool done = false;\n do {\n try {\n DType x = 0, y = 0;\n done = !data_tsv.read_row(x, y);\n if (!done) {\n raw_data_x.push_back(x);\n raw_data_y.push_back(y);\n }\n } catch (const io::error::no_digit& err) {\n // ignore bad formated samples\n std::cout << err.what() << std::endl;\n }\n } while (!done);\n\n // shuffle data\n size_t seed = 3465467546;\n std::shuffle(raw_data_x.begin(), raw_data_x.end(),\n std::default_random_engine(seed));\n std::shuffle(raw_data_y.begin(), raw_data_y.end(),\n std::default_random_engine(seed));\n\n // map data to the tensor\n size_t rows = raw_data_x.size();\n const auto data_x = Eigen::Map(raw_data_x.data(), rows, 1);\n std::cout << \"X shape \" << data_x.rows() << \":\" << data_x.cols() << std::endl;\n Matrix x;\n std::tie(x, std::ignore, std::ignore) = standardize(data_x);\n\n const auto data_y = Eigen::Map(raw_data_y.data(), rows, 1);\n std::cout << \"Y shape \" << data_y.rows() << \":\" << data_y.cols() << std::endl;\n // I'm not using structured binding, because hard to debug such values\n Matrix y;\n DType ym{0};\n DType ysd{0};\n std::tie(y, ym, ysd) = standardize(data_y);\n\n // Scale data to prevent float overflow in BGD\n size_t p_degree = 64;\n const DType scale = 0.6;\n x *= scale;\n y *= scale;\n\n // solve normal equation\n Matrix poly_x = generate_polynomial(x, p_degree);\n Matrix b_eq =\n (poly_x.transpose() * poly_x).ldlt().solve(poly_x.transpose() * y);\n auto cost =\n (y - poly_x * b_eq).array().pow(2.f).sum() / static_cast(rows);\n std::cout << \"cost for normal equation solution : \" << cost << std::endl;\n\n // optimize with BGD\n Matrix b = bgd(poly_x, y);\n\n // generate new data\n const size_t new_x_size = 500;\n std::vector x_coord(new_x_size);\n auto new_x = Eigen::Map(x_coord.data(), new_x_size, 1);\n new_x = Eigen::Matrix::LinSpaced(\n new_x_size, data_x.minCoeff(), data_x.maxCoeff());\n Matrix new_x_std;\n std::tie(new_x_std, std::ignore, std::ignore) = standardize(new_x);\n new_x_std *= scale;\n Matrix new_poly_x = generate_polynomial(new_x_std, p_degree);\n\n // make predictions\n std::vector polyline_eq(new_x_size);\n auto new_y_eq = Eigen::Map(polyline_eq.data(), new_x_size, 1);\n new_y_eq = new_poly_x * b_eq;\n\n std::vector polyline(new_x_size);\n auto new_y = Eigen::Map(polyline.data(), new_x_size, 1);\n new_y = new_poly_x * b;\n\n // restore scalenew_y\n new_y_eq /= scale;\n new_y_eq = (new_y_eq * ysd).array() + ym;\n\n new_y /= scale;\n new_y = (new_y * ysd).array() + ym;\n\n // plot the data we read and approximate\n plotcpp::Plot plt(true);\n plt.SetTerminal(\"qt\");\n plt.SetTitle(\"Web traffic over the last month\");\n plt.SetXLabel(\"Time\");\n plt.SetYLabel(\"Hits/hour\");\n plt.SetAutoscale();\n plt.GnuplotCommand(\"set grid\");\n\n auto time_range = data_x.maxCoeff() - data_x.minCoeff();\n auto tic_size = 7 * 24;\n auto time_tics = time_range / tic_size;\n plt.SetXRange(-tic_size / 2, data_x.maxCoeff() + tic_size / 2);\n\n plotcpp::Plot::Tics xtics;\n for (size_t t = 0; t < time_tics; ++t) {\n xtics.push_back({\"week \" + std::to_string(t), t * tic_size});\n }\n plt.SetXTics(xtics);\n\n plt.Draw2D(plotcpp::Points(raw_data_x.begin(), raw_data_x.end(),\n raw_data_y.begin(), \"data\", \"lc rgb 'black' pt 1\"),\n plotcpp::Lines(x_coord.begin(), x_coord.end(), polyline_eq.begin(),\n \"neq approx\", \"lc rgb 'red' lw 2\"),\n plotcpp::Lines(x_coord.begin(), x_coord.end(), polyline.begin(),\n \"bgd approx\", \"lc rgb 'cyan' lw 2\"));\n plt.Flush();\n\n return 0;\n}\n", "meta": {"hexsha": "93344bb57cdac42ff88bee8f311fd1af40c19a23", "size": 6804, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "polynomial_regression_eigen/poly_reg_eigen.cpp", "max_stars_repo_name": "yf225/mlcpp", "max_stars_repo_head_hexsha": "12d6f8224d7d6305a191c7afd2d5510e0a15299f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 268.0, "max_stars_repo_stars_event_min_datetime": "2018-04-11T15:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T08:18:03.000Z", "max_issues_repo_path": "polynomial_regression_eigen/poly_reg_eigen.cpp", "max_issues_repo_name": "soma2000-lang/mlcpp", "max_issues_repo_head_hexsha": "afb08c0c81bdd2c68710831e8d4b233005ab3750", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2019-02-10T22:19:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-23T05:55:50.000Z", "max_forks_repo_path": "polynomial_regression_eigen/poly_reg_eigen.cpp", "max_forks_repo_name": "soma2000-lang/mlcpp", "max_forks_repo_head_hexsha": "afb08c0c81bdd2c68710831e8d4b233005ab3750", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 67.0, "max_forks_repo_forks_event_min_datetime": "2018-04-19T21:15:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T17:11:00.000Z", "avg_line_length": 29.9735682819, "max_line_length": 132, "alphanum_fraction": 0.6196355085, "num_tokens": 2023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.776302898917712}} {"text": "#include \n#include \n#include \n#include \n\n// computes the center of a circle from 3 points on its boundary\nEigen::Vector2d circleCenter(const Eigen::Vector2d &P1, const Eigen::Vector2d &P2, const Eigen::Vector2d &P3)\n{\n\tEigen::Matrix mat;\n\tmat.block<1,2>(0,0) = (P2 - P1).transpose();\n\tmat.block<1,2>(1,0) = (P3 - P2).transpose();\n\tmat.block<1,2>(2,0) = (P1 - P3).transpose();\n\t\n\tEigen::Vector3d vec;\n\tvec.x() = 0.5*(P2 - P1).squaredNorm() + (P2 - P1).dot(P1);\n\tvec.y() = 0.5*(P3 - P2).squaredNorm() + (P3 - P2).dot(P2);\n\tvec.z() = 0.5*(P1 - P3).squaredNorm() + (P1 - P3).dot(P3);\n\t\n\treturn mat.colPivHouseholderQr().solve(vec);\n}\n\n\nint main(int argc, char** argv)\n{\n\tdouble t = 0.21111111111111111111111111111111111111111111111111111111111;\n\tEigen::Vector2d P1( 0.0, 0.0),\n\t\t\t\t\tP2( 1.0, 0.0),\n\t\t\t\t\tP3( 1.0, 1.0),\n\t\t\t\t\tP4( 0.0, 1.0);\n\tEigen::Matrix2d mat;\n\tmat << 1.0, 0.0,\n\t\t 0.0, 1.0;\n\tEigen::Vector2d tr(0.8,0.6);\n\tP1 = t*mat*P1 + tr;\n\tP2 = t*mat*P2 + tr;\n\tP3 = t*mat*P3 + tr;\n\tP4 = t*mat*P4 + tr;\n\t\n\tEigen::Vector2d C = circleCenter(P1,P2,P3);\n\n\tdouble d1 = (C - P1).norm(),\n\t\t d2 = (C - P2).norm(),\n\t\t d3 = (C - P3).norm(),\n\t\t d4 = (C - P4).norm();\n\t\n\tstd::cout.precision(100);\n\tstd::cout << \"d1 \" << d1 << std::endl;\n\tstd::cout << \"d2 \" << d2 << std::endl;\n\tstd::cout << \"d3 \" << d3 << std::endl;\n\tstd::cout << \"d4 \" << d4 << std::endl;\n\t\n\tstd::cout << std::endl;\n\tstd::cout << \"Test d4 == d1\" << std::endl;\n\tif(d4 == d1)\n\t\tstd::cout << \"Distances égales\" << std::endl;\n\telse\n\t\tstd::cout << \"Distances non égales\" << std::endl;\n\t\n\tstd::cout << std::endl;\n\tstd::cout << \"Test std::abs(d1 - d4) <= std::min(d1,d4)*std::numeric_limits::epsilon()\" << std::endl;\n\tif( std::abs(d1 - d4) <= std::min(d1,d4)*std::numeric_limits::epsilon() )\n\t\tstd::cout << \"Distances égales\" << std::endl;\n\telse\n\t\tstd::cout << \"Distances non égales\" << std::endl;\n\t\n\tstd::cout << std::endl;\n\tstd::cout << \"Test std::abs(d1 - d4) <= 6.0*std::min(d1,d4)*std::numeric_limits::epsilon()\" << std::endl;\n\tif( std::abs(d1 - d4) <= 6.0*std::min(d1,d4)*std::numeric_limits::epsilon() )\n\t\tstd::cout << \"Distances égales\" << std::endl;\n\telse\n\t\tstd::cout << \"Distances non égales\" << std::endl;\n\t\n\tstd::cout << std::endl;\n\tstd::cout << \"Test std::abs(d1 - d4) <= 7.0*std::min(d1,d4)*std::numeric_limits::epsilon()\" << std::endl;\n\tif( std::abs(d1 - d4) <= 7.0*std::min(d1,d4)*std::numeric_limits::epsilon() )\n\t\tstd::cout << \"Distances égales\" << std::endl;\n\telse\n\t\tstd::cout << \"Distances non égales\" << std::endl;\n\t\n\tstd::cout << std::endl;\n\tstd::cout << \"Test (float)d4 == (float)d1\" << std::endl;\n\tif((float)d4 == (float)d1)\n\t\tstd::cout << \"Distances égales\" << std::endl;\n\telse\n\t\tstd::cout << \"Distances non égales\" << std::endl;\n\t\n\tstd::cout << std::abs(d1+1.0) << \" \" << abs(d1+1.0) << std::endl;\n\t\n\treturn 0;\n}\n", "meta": {"hexsha": "a1b3fced79801dc77330cc8ff2e5d3f78516614e", "size": 2894, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "Ibujah/doubleprecision", "max_stars_repo_head_hexsha": "c184e02046f8343624c83ab4c7ee5229b4be2e45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "Ibujah/doubleprecision", "max_issues_repo_head_hexsha": "c184e02046f8343624c83ab4c7ee5229b4be2e45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "Ibujah/doubleprecision", "max_forks_repo_head_hexsha": "c184e02046f8343624c83ab4c7ee5229b4be2e45", "max_forks_repo_licenses": ["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.8021978022, "max_line_length": 114, "alphanum_fraction": 0.5825846579, "num_tokens": 1137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7761083062484054}} {"text": "#include \n\n#include \n\n/* @brief\n * @param[in] z An $n$-dimensional vector containing one side of input data\n * @param[in] c An $n$-dimensional vector containing the other side of input data\n * @param[out] x The vector of parameters $(\\alpha,\\beta)$, intercept and slope of the line fitted\n */\nEigen::Vector2d lsqEst(const Eigen::VectorXd &z, const Eigen::VectorXd &c) {\n\tEigen::Vector2d x;\n\tint n = z.size();\n\n\tEigen::MatrixXd A(n, 2);\n\tA.col(0) = z;\n\tA(0, 1) = z(1);\n\tA(n - 1, 1) = z(n - 2);\n\n\tfor(int i = 1; i < n - 1; i++) {\n\t\tA(i, 1) = z(i - 1) + z(i + 1);\n\t}\n\n\tx = (A.transpose() * A).llt().solve(A.transpose() * c);\n\n\treturn x;\n}\n\nint main() {\n int n = 10;\n Eigen::VectorXd z(n), c(n);\n for(int i = 0; i < n; ++i) {\n\t\tz(i) = i + 1;\n\t\tc(i) = n - i;\n\t}\n\n\tEigen::Vector2d x = lsqEst(z, c);\n\n\tstd::cout << \"alpha = \" << x(0) << std::endl;\n\tstd::cout << \"beta = \" << x(1) << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "c0d8fbdd2c23c8a3eb6ddc7fdef3ac607db8e75c", "size": 934, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "exercise_3/tridiag_least_squares.cpp", "max_stars_repo_name": "azurite/numCSE18-code", "max_stars_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-13T19:08:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-13T19:08:32.000Z", "max_issues_repo_path": "exercise_3/tridiag_least_squares.cpp", "max_issues_repo_name": "azurite/numCSE18-code", "max_issues_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercise_3/tridiag_least_squares.cpp", "max_forks_repo_name": "azurite/numCSE18-code", "max_forks_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_forks_repo_licenses": ["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.7209302326, "max_line_length": 98, "alphanum_fraction": 0.5535331906, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.946596665680527, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7761082959065193}} {"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_CBRT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_CBRT_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n @ingroup group-exponential\n Function object implementing cbrt capabilities\n\n Compute the cubic root: \\f$\\sqrt[3]{x}\\f$\n\n @par Semantic:\n\n For every parameter of floating type T\n\n @code\n T r = cbrt(x);\n @endcode\n\n is similar to:\n\n @code\n T r = pow(x, T(1/3.0));\n @endcode\n\n but not equivalent because pow cannot raise a negative base to a fractional exponent.\n we have for all non Nan floating values cbrt(-x) = -cbrt(x).\n\n @par Decorators\n\n std_ for floating entries\n\n @see pow, sqrt\n\n **/\n Value cbrt(Value const & v0);\n} }\n#endif\n\n#include \n#include \n\n#endif\n", "meta": {"hexsha": "0e91c9679c47019f08ef773e49be55cb458379e8", "size": 1240, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/cbrt.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/cbrt.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/cbrt.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 21.7543859649, "max_line_length": 100, "alphanum_fraction": 0.5790322581, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455085, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7760974544417659}} {"text": "/////////////\n///\n/// Constants.h\n/// Constant miscellanea!!\n///\n////////\n\n\n#ifndef ____CONSTANTS__\n#define ____CONSTANTS__\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#define ARMA_DONT_USE_WRAPPER\n// Take care with this macro: Use wisely!!!\n#define ARMA_NO_DEBUG\n#include \n\ntypedef std::complex dcomplex;\n/* typedef std::vector> matrix; */\n/* typedef std::vector> cmatrix; */\n\nusing namespace std;\n//using namespace arma;\n//cout.precision(15);\n\n/// Complex numbers\nconst dcomplex Im {0.0,1.0};\nconst dcomplex One {1.0,0.0};\nconst dcomplex Zero {0.0,0.0};\n\n/// pi\nconst double pi = 4.0*atan(1.0);\nconst double twopi = 2.0 * pi;\nconst double one_over_pi = 1.0 / pi;\n\n/// Square root two\nconst double sqrt_two = sqrt(2.0);\nconst double one_over_sqrt_two = 1.0 / sqrt_two;\n\n/// Speed of light, in a.u. units\nconst double speed_light = 137.0; \nconst double one_over_speed_light = 1.0 / speed_light;\n// Speed of light in meters over seconds \nconst double speed_light_is = 2.99792458e8;\n\n/// electron charge\nconst double charge_electron_au = -1.;\n/// Proton mass\nconst double mass_proton_au = 1836.;\n/// Bohr radius (IS)\nconst double bohr_radius = 5.29177211e-11;\nconst double aulength_nm = 5.29177211e-2;\nconst double hatree_to_eV = 27.211;\n// au time\nconst double autime_fs = 2.418884326505e-2;\nconst double autime_s = 2.418884326505e-17;\n// au intensity\nconst double auintensity = 3.5e16;\n\n#endif // ____constants__ //\n\n\n", "meta": {"hexsha": "f30abce44b09e8c2ad39a927da3a891ed93d649f", "size": 1649, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/constants.hpp", "max_stars_repo_name": "itsAlexNoir/montecorvo", "max_stars_repo_head_hexsha": "69040d587f28c419929f9e3e3641de8a5c9d41c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/constants.hpp", "max_issues_repo_name": "itsAlexNoir/montecorvo", "max_issues_repo_head_hexsha": "69040d587f28c419929f9e3e3641de8a5c9d41c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/constants.hpp", "max_forks_repo_name": "itsAlexNoir/montecorvo", "max_forks_repo_head_hexsha": "69040d587f28c419929f9e3e3641de8a5c9d41c3", "max_forks_repo_licenses": ["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.5890410959, "max_line_length": 57, "alphanum_fraction": 0.7058823529, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.7759852604624635}} {"text": "/**\n * This file is part of https://github.com/adrelino/interpolation-methods\n *\n * Copyright (c) 2018 Adrian Haarbach \n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n#ifndef INTERPOL_SU2_HPP\n#define INTERPOL_SU2_HPP\n\n#include \n#include \n\n/**\n * Sinus cardinalis. Not normed version\n * @param t\n * @return sin(t)/t\n */\ntemplate\nT sinc(T theta) {\n return std::sin(theta) / theta; //si\n //return sin(M_PI*theta) / (M_PI*theta); normed //sinc\n}//needed in QuaternionMapping.h\n\n#include \n\n//using namespace px; //to import logq, expq into global namespace!\n\n\n//Added to namespace Eigen so that ADL works (otherwise won't compile on CLANG: https://clang.llvm.org/compatibility.html#dep_lookup)\nnamespace Eigen {\n/**\n * Exp map applied to quaternions.\n *\n * The usual exp : so(3) -> SO(3) maps\n * from the Lie algebra (a tangent space) so(3) of skew-symmetric matrices of the from [wx,wy,wz]_x\n * to the Lie group (a smooth manifold) SO(3) of orthonormal rotation matrices : R e 3x3 : RR^T=I, |R|=1\n *\n * https://github.com/hengli/vmav-ros-pkg/blob/master/calibration/hand_eye_calibration/include/hand_eye_calibration/QuaternionMapping.h\n *\n * @param q' so(3) tangent space quaternion (if it was unit quaternion before, then its w is 0)\n * @return q = exp(q') SO(3) group quaternion\n */\ntemplate\ninline Eigen::Quaternion expq(const Eigen::Quaternion &q) {\n return px::expq(q);\n /*T a = q.vec().norm();\n T exp_w = std::exp(q.w());\n\n if (a == T(0)) {\n return Eigen::Quaternion(exp_w, T(0), T(0), T(0));\n }\n\n Eigen::Quaternion res;\n res.w() = exp_w * T(std::cos(a));\n res.vec() = exp_w * T(sinc(a)) * q.vec();\n\n return res;*/\n\n// assertCustom(q.w() == T(0));\n// Eigen::AngleAxis angleAxis;\n// T angle = q.vec().norm();\n// angleAxis.axis() = q.vec() / angle;\n// angleAxis.angle() = angle * T(2.0);\n//\n// Eigen::Quaternion res(angleAxis);\n// return res;\n}\n\n/**\n * Log map applied to quaternions.\n *\n * If q was a unit quaternion, then w will be 0 in q' (since log(1)=0)\n *\n * The usual log : SO(3) -> so(3) maps\n * from the Lie group (a smooth manifold) SO(3) of orthonormal rotation matrices : R e 3x3 : RR^T=I, |R|=1\n * to the Lie algebra (a tangent space) so(3) of skew-symmetric matrices of the from [wx,wy,wz]_x\n *\n * https://github.com/hengli/vmav-ros-pkg/blob/master/calibration/hand_eye_calibration/include/hand_eye_calibration/QuaternionMapping.h\n *\n * @param q SO(3) group quaternion\n * @return q' = log(q) so(3) tangent space quaternion\n */\ntemplate\ninline Eigen::Quaternion logq(Eigen::Quaternion q) {\n return px::logq(q);\n /*\n\n //if(q.w()(w, T(0), T(0), T(0));\n }\n\n Eigen::Quaternion res;\n res.w() = w;\n res.vec() = q.vec() / exp_w / (sinc(a));\n\n return res;//.normalized();\n */\n\n// assertCustom(abs(q.norm() - T(1)) < T(0.1));\n// Eigen::AngleAxis angleAxis(q);\n// Eigen::Quaternion res;\n// res.w() = T(0);\n// res.vec() = angleAxis.axis() * angleAxis.angle() * T(0.5);\n// return res;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n//printing of Quaternion, Vector3 and Map works with this (even for Ceres Jet types)\ntemplate\nstatic std::ostream &operator<<(std::ostream &stream, const Eigen::QuaternionBase &q) {\n return stream << std::setprecision(2) << std::fixed << q.w() << \", \" << q.x() << \", \" << q.y() << \", \" << q.z();\n}\ntemplate\nstatic std::ostream &operator<<(std::ostream &stream, const Eigen::Matrix &q) {\n return stream << std::setprecision(2) << std::fixed << q.x() << \", \" << q.y() << \", \" << q.z();\n}\ntemplate\nstatic std::ostream &operator<<(std::ostream &stream, const Eigen::Map> &q) {\n return stream << std::setprecision(2) << std::fixed << q.x() << \", \" << q.y() << \", \" << q.z();\n}\n\n/**\n * Addition of quaternion coefficients.\n * \\warning This operation has no direct geometric interpretation, and in the general case result in a non unit quaternion.\n * @return the addition of \\c *this and \\a other\n */\ntemplate\nstatic Eigen::Quaternion operator+(const Eigen::Quaternion &a, const Eigen::Quaternion &b) {\n return Eigen::Quaternion(a.coeffs() + b.coeffs());\n}\n/**\n * Substraction of quaternion coefficients.\n * \\warning This operation has no direct geometric interpretation, and in the general case result in a non unit quaternion.\n * @return the substraction of \\c *this and \\a other\n */\ntemplate\nstatic Eigen::Quaternion operator-(const Eigen::Quaternion &a, const Eigen::Quaternion &b) {\n return Eigen::Quaternion(a.coeffs() - b.coeffs());\n}\n/**\n * Lhs multiplication of quaternion coefficients with a scalar.\n * Only useful in log space of unit quaternion (when w==0)\n */\ntemplate\nstatic Eigen::Quaternion operator*(const T &b, const Eigen::Quaternion &a) {\n return Eigen::Quaternion(a.coeffs() * b);\n}\n/**\n * Rhs multiplication of quaternion coefficients with a scalar.\n * Only useful in log space of unit quaternion (when w==0)\n */\ntemplate\nstatic Eigen::Quaternion operator*(const Eigen::Quaternion &a, const T &b) {\n return Eigen::Quaternion(a.coeffs() * b);\n};\n\n} // ns Eigen\n\n#endif // INTERPOL_SU2_HPP\n", "meta": {"hexsha": "8b1c6f7ac3462e4f09210d924d9a2ee11f81e89e", "size": 5637, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libinterpol/include/interpol/orientation/SU2.hpp", "max_stars_repo_name": "adrelino/interpolation-methods", "max_stars_repo_head_hexsha": "094cbabbd0c25743d088a623f5913149c6b8a2ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 81.0, "max_stars_repo_stars_event_min_datetime": "2018-08-31T03:26:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T04:01:44.000Z", "max_issues_repo_path": "src/libinterpol/include/interpol/orientation/SU2.hpp", "max_issues_repo_name": "bygreencn/interpolation-methods", "max_issues_repo_head_hexsha": "508723d1bca10c350f1a83c2fd31c2227cc1c0a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-16T06:45:12.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-15T17:47:01.000Z", "max_forks_repo_path": "src/libinterpol/include/interpol/orientation/SU2.hpp", "max_forks_repo_name": "bygreencn/interpolation-methods", "max_forks_repo_head_hexsha": "508723d1bca10c350f1a83c2fd31c2227cc1c0a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T18:37:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T15:04:37.000Z", "avg_line_length": 31.4916201117, "max_line_length": 135, "alphanum_fraction": 0.6432499557, "num_tokens": 1634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308054739519, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7758145168181555}} {"text": "//\n// This program is used to study how to calculate (SS|SS)^{m}\n// for the recursive relation. Basically, it focus on the \n// fmt function:\n// f_{m}(t) = \\int^{1}_{0} u^{2m} e^{-tu^{2}} du \n// it needs the boost library to calcualte fmt\n// fenglai liu\n// Oct. 2013\n//\n// for reference, see Harris paper and the reference cited inside:\n// Harris, Frank E\n// Evaluation of GTO molecular integrals\n// International Journal of Quantum Chemistry, 1983, Vol. 23, Page 1469--1478\n//\n// note:\n// we found that the approximation of (2m-1)!!/R expression is \n// not numerical stable. Combined with down recursive relation,\n// it introduces greater error compared with other methods. \n// Therefore we finally abadon it.\n//\n//\n//\n\n// common C head files used in the program\n#include\n#include\n\n// external math functions \n#include\n\n// common C++ head files may be used in the program\n#include\n#include\n#include\n#include \n#include\n#include\n#include\n#include\n#include\n#include\n\n#include // special functions in math\n#include \n#include \n#include \nusing namespace boost::math;\nusing namespace boost;\nusing namespace std;\n#define PI 3.1415926535897932384626E0 \n\ndouble fm(const double& a, const int& m); \ndouble doubleFac(const int& m, const int& n); \n\ndouble fm(const double& a, const int& m) {\n\tdouble x = 1.0E0;\n\tif (fabs(a)<1.0E-14) return (pow(x,2*m+1)/(2*m+1));\n\tdouble f12 = 1.0E0/2.0E0;\n\tdouble p = 1.0E0/(2.0E0*pow(a,m+f12));\n\tdouble upperLimit = a*pow(x,2.0E0);\n\treturn tgamma_lower(m+f12,upperLimit)*p;\n}\n\ndouble doubleFac(const int& m, const int& n) {\n\t// calculate (2m-1)!!/(2m+2n+1)!!\n\tdouble x = 1.0E0;\n\tfor(int i=0; i<=n; i++) {\n\t\tx *= 1.0E0/(2*m+2*i+1); \n\t}\n\treturn x;\n} \n\nint main() \n{\n\t///////////////////////////////////////////////////\n\t// global settings\n\t// step length and number of claculation for \n\t// time performance\n\t// global error is the error range\n\t// if the difference is less than the error, we \n\t// think the error could be omitted\n\t///////////////////////////////////////////////////\n\tint N = 10000000;\n\tdouble steplength = 0.000001;\n\tdouble globalError = 1.0E-10;\n\tint M_limmit = 10;\n\tint top_M_limmit = 30;\n\tdouble T_max_limit = 36.0E0;\n\tdouble T_min_limit = 1.1E0;\n\n\tfloat steplength_f = 0.00001;\n\tfloat globalError_f = 1.0E-6;\n\n\t/*\n\t///////////////////////////////////////////////////\n\t// this section testing the timing performance\n\t// between the different functions\n\t// so far, erf is 160 faster than the fmt function\n\t// in boost library\n\t///////////////////////////////////////////////////\n\tcout << \"===========================================================\" << endl;\n\tcout << \"Time performance result: \" << endl;\n\tcout << \"Total sample number is \" << N << endl;\n\tcout << \"===========================================================\" << endl;\n\t// testing the erf\n\ttimer t1;\n\tfor(int i=0; iglobalError) {\n\t\t\t\tprintf(\"fmt is %-14.12f\\n\", s);\n\t\t\t\tprintf(\"T is %-14.12f\\n\", T);\n\t\t\t\tprintf(\"error/fmt is %-14.12f\\n\", d/fmt);\n\t\t\t\tprintf(\"for m=%d difference is %-14.12f\\n\", i, d);\n\t\t\t}\n\t\t\te0 = e;\n\t\t}\n\t}\n\t*/\n\n\t/*\n\t///////////////////////////////////////////////////\n\t// testing the fmt from down recursive relation\n\t///////////////////////////////////////////////////\n\tcout << endl << endl;\n\tcout << \"===========================================================\" << endl;\n\tcout << \"testing the down recursive relation for m = 1 to \" << top_M_limmit << endl;\n\tcout << \"this is for double type variable\" << endl;\n\tcout << \"error range is \" << globalError << endl;\n\tcout << \"step length for T is \" << steplength << endl;\n\tcout << \"T is ranging from 0 \" << \" to \" <=0; i--) {\n\t\t\t\tdouble s = fm(T,i);\n\t\t\t\tdouble e = (1.0/(2*i+1.0))*(t2*e0+et);\n\t\t\t\tdouble d = fabs(s-e);\n\t\t\t\tif (d>globalError) {\n\t\t\t\t\tprintf(\"T is %-14.12f\\n\", T);\n\t\t\t\t\tprintf(\"for m=%d difference is %-14.12f\\n\", n, d);\n\t\t\t\t}\n\t\t\t\te0 = e;\n\t\t\t}\n\t\t}\n\t}\n\t*/\n\n\t/*\n\tcout << endl << endl;\n\tcout << \"===========================================================\" << endl;\n\tcout << \"testing the down recursive relation for m = 1 to \" << top_M_limmit << endl;\n\tcout << \"this is for float type variable\" << endl;\n\tcout << \"error range is \" << globalError_f << endl;\n\tcout << \"step length for T is \" << steplength_f << endl;\n\tcout << \"T is ranging from 0 \" << \" to \" <=0; i--) {\n\t\t\t\tfloat s = fm(T,i);\n\t\t\t\tfloat e = (1.0/(2*i+1.0))*(t2*e0+et);\n\t\t\t\tfloat d = fabs(s-e);\n\t\t\t\tif (d>globalError_f) {\n\t\t\t\t\tprintf(\"T is %-10.7f\\n\", T);\n\t\t\t\t\tprintf(\"for m=%d difference is %-10.7f\\n\", n, d);\n\t\t\t\t}\n\t\t\t\te0 = e;\n\t\t\t}\n\t\t}\n\t}\n\t*/\n\n\t/*\n\t///////////////////////////////////////////////////\n\t// testing the fmt from down recursive relation\n\t// this is not so accurate\n\t// abandoned, too\n\t///////////////////////////////////////////////////\n\tcout << endl << endl;\n\tcout << \"===========================================================\" << endl;\n\tcout << \"testing the down recursive relation for m = 1 to 10\" << endl;\n\tcout << \"the fm(t) is approximated by (2m-1)!!/(2t)^{m}*t^{1/2}\" << endl;\n\tcout << \"error range is 1.0E-10\" << endl;\n\tcout << \"step length for T is \" << steplength << \" from 30.0 to 50.0\" << endl;\n\tcout << \"===========================================================\" << endl;\n\tint numSteps = (50-30)/steplength;\n\tdouble globalError = 1.0E-9;\n\tfor (int n=1; n<=10; n++) {\n\t\tfor (int j = 0; j=1; k--) {\n\t\t\t\tfmt *= (2*k-1)/(2.0*T);\n\t\t\t}\n\t\t\tdouble s0 = fm(T,n);\n\t\t\tdouble d0 = fabs(s0-fmt);\n\t\t\tif (d0>globalError) {\n\t\t\t\tprintf(\"T is %-14.12f\\n\", T);\n\t\t\t\tprintf(\"error/fmt is %-14.12f\\n\", d0/fmt);\n\t\t\t\tprintf(\"for m=%d difference is %-14.12f\\n\", n, d0);\n\t\t\t}\n\n\t\t\t// recursive relation\n\t\t\tdouble et = exp(-T);\n\t\t\tdouble e0 = fmt;\n\t\t\tdouble t2 = 2.0*T;\n\t\t\tfor(int i=n-1; i>=0; i--) {\n\t\t\t\tdouble s = fm(T,i);\n\t\t\t\tdouble e = (1.0/(2*i+1.0))*(t2*e0+et);\n\t\t\t\tdouble d = fabs(s-e);\n\t\t\t\tif (d>globalError) {\n\t\t\t\t\tprintf(\"T is %-14.12f\\n\", T);\n\t\t\t\t\tprintf(\"error/fmt is %-14.12f\\n\", d/s);\n\t\t\t\t\tprintf(\"for m=%d difference is %-14.12f\\n\", n, d);\n\t\t\t\t}\n\t\t\t\te0 = e;\n\t\t\t}\n\t\t}\n\t}\n\t*/\n\n\t/*\n\t///////////////////////////////////////////////////\n\t// testing the power series\n\t// equation of 9 in Harris paper\n\t// We try to expand the power series up to 10 terms\n\t// here we test from m=1 to m=10\n\t// for T from 0 to 1.1\n\t///////////////////////////////////////////////////\n\tnumSteps = T_min_limit/steplength;\n\tcout << endl << endl;\n\tcout << \"===========================================================\" << endl;\n\tcout << \"testing the power series expansion with 13 terms\" << endl;\n\tcout << \"this is for double type variable\" << endl;\n\tcout << \"error range is \" << globalError << endl;\n\tcout << \"step length for T is \" << steplength << endl;\n\tcout << \"T is ranging from 0 to \" << T_min_limit << endl;\n\tcout << \"===========================================================\" << endl;\n\tfor (int m = 1; m<=M_limmit; m++) {\n\t\tfor (int j = 0; j=1; i--) {\n\t\t\t\tx = 1.0+t2/(2.0*(m+i)+1.0)*x;\n\t\t\t}\n\t\t\tx = (1.0/(2*m+1))*x;\n\t\t\tx *= et;\n\t\t\tdouble result = fm(T,m);\n\t\t\tdouble d = fabs(result-x);\n\t\t\tif (d>globalError) {\n\t\t\t\tprintf(\"fmt is %-16.14f\\n\", result);\n\t\t\t\tprintf(\"for m=%d T=%f difference is %-16.14f\\n\", m, T, d);\n\t\t\t}\n\t\t}\n\t}\n\t*/\n\n\t/*\n\tcout << endl << endl;\n\tcout << \"===========================================================\" << endl;\n\tcout << \"testing the power series expansion with 13 terms\" << endl;\n\tcout << \"this is for float type variable\" << endl;\n\tcout << \"error range is \" << globalError_f << endl;\n\tcout << \"step length for T is \" << steplength_f << endl;\n\tcout << \"T is ranging from 0 to \" << T_min_limit << endl;\n\tcout << \"===========================================================\" << endl;\n\tnumSteps = T_min_limit/steplength_f;\n\tfor (int m = 1; m<=M_limmit; m++) {\n\t\tfor (int j = 0; j=1; i--) {\n\t\t\t\tx = 1.0+t2/(2.0*(m+i)+1.0)*x;\n\t\t\t}\n\t\t\tx = (1.0/(2*m+1))*x;\n\t\t\tx *= et;\n\t\t\tdouble result = fm(T,m);\n\t\t\tdouble d = fabs(result-x);\n\t\t\tif (d>globalError_f) {\n\t\t\t\tprintf(\"fmt is %-16.14f\\n\", result);\n\t\t\t\tprintf(\"for m=%d T=%f difference is %-16.14f\\n\", m, T, d);\n\t\t\t}\n\t\t}\n\t}\n\t*/\n\n\t////////////////////////////////////////////////////////\n\t// this is the continuous fraction implementation\n\t// of Harris equation, not correct yet, already abandoned\n\t// equation 24\n\t// testing the series\n\t// for m = 0, and T is from 0.01 to 25\n\t// test the convergence for the series\n\t////////////////////////////////////////////////////////\n\t/*\n\tint n = 20;\n\tfor (int m=0; m<=30; m++) {\n\t\tfor (int j = 0; j<2500; j++) {\n\t\t\tdouble T = 0.01*(j+1);\n\t\t\tdouble et = exp(-T);\n\t\t\tdouble minusn = 1.0E0;\n\t\t\tif ((n+1)%2 == 1) minusn = -1.0E0;\n\t\t\tdouble an = 2.0*(minusn*(m+n)-(m+1))/(4.0*(m+n)*(m+n)-1);\n\t\t\tdouble x = 1+an*T;\n\t\t\tfor(int i=n-1; i>1; i--) {\n\t\t\t\tdouble minusi = 1.0E0;\n\t\t\t\tif ((i+1)%2 == 1) minusi = -1.0E0;\n\t\t\t\tdouble ai = 2.0*(minusi*(m+i)-(m+1))/(4.0*(m+i)*(m+i)-1);\n\t\t\t\tx = (1+ai*T)/x;\n\t\t\t}\n\t\t\tdouble a1 = 2.0/(4.0*(m+1)*(m+1)-1);\n\t\t\tx = a1*T/x;\n\t\t\tx += 1/(2*m+1);\n\t\t\tx *= et;\n\t\t\tdouble result = fm(T,m);\n\t\t\tdouble d = fabs(result-x);\n\t\t\tif (d>0.00000000000001) {\n\t\t\t\tprintf(\"for %d %f difference is %-16.14f\\n\", m, T, d);\n\t\t\t}\n\t\t}\n\t}\n\t*/\n\n\treturn 0;\n}\n", "meta": {"hexsha": "7dc1e41fbb2911be088b9b429da52e1e90f201e9", "size": 12225, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "util/fmt_test/fmt_test_old.cpp", "max_stars_repo_name": "murfreesboro/cppints", "max_stars_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "util/fmt_test/fmt_test_old.cpp", "max_issues_repo_name": "murfreesboro/cppints", "max_issues_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "util/fmt_test/fmt_test_old.cpp", "max_forks_repo_name": "murfreesboro/cppints", "max_forks_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2599009901, "max_line_length": 85, "alphanum_fraction": 0.5048670757, "num_tokens": 3844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7755581786074037}} {"text": "#include \"EigenUtilities.h\"\n\n#include \n#include \n\n#include \n\n// Keep these utilities separate as using Eigen in an existing source\n// file results in a 50% increase in compilation time.\n\n// Compute the best-fitting projective transform that maps a set of 3D points\n// to 2D points.\n// A best-fit linear transform could be created by eliminating the denominators below.\nvoid usgscsm::computeBestFitProjectiveTransform(std::vector const& imagePts,\n std::vector const& groundPts,\n std::vector & transformCoeffs) {\n \n if (imagePts.size() != groundPts.size()) \n throw csm::Error(csm::Error::INVALID_USE,\n \"The number of inputs and outputs must agree.\",\n \"computeBestFitProjectiveTransform\");\n \n int numPts = imagePts.size();\n if (numPts < 8)\n throw csm::Error(csm::Error::INVALID_USE,\n \"At least 8 points are needed to fit a 3D-to-2D projective transform. \"\n \"Ideally more are preferred.\",\n \"computeBestFitProjectiveTransform\");\n\n int numMatRows = 2 * numPts; // there exist x and y coords for each point\n int numMatCols = 14; // Number of variables in the projective transform\n \n Eigen::MatrixXd M = Eigen::MatrixXd::Zero(numMatRows, numMatCols);\n Eigen::VectorXd b = Eigen::VectorXd::Zero(numMatRows);\n \n for (int it = 0; it < numPts; it++) {\n\n double x = groundPts[it].x, y = groundPts[it].y, z = groundPts[it].z;\n double r = imagePts[it].line, c = imagePts[it].samp;\n\n // If the solution coefficients are u0, u1, ..., must have:\n \n // (u0 + u1 * x + u2 * y + u3 * z) / (1 + u4 * x + u5 * y + u6 * z) = r\n // (u7 + u8 * x + u9 * y + u10 * z) / (1 + u11 * x + u12 * y + u13 * z) = c\n\n // Multiply by the denominators. Get a linear regression in the coefficients.\n \n M.row(2 * it + 0) << 1, x, y, z, -x * r, -y * r, -z * r, 0, 0, 0, 0, 0, 0, 0;\n M.row(2 * it + 1) << 0, 0, 0, 0, 0, 0, 0, 1, x, y, z, -x * c, -y * c, -z * c;\n\n b[2 * it + 0] = r;\n b[2 * it + 1] = c;\n }\n\n // Solve the over-determined system, per:\n // https://eigen.tuxfamily.org/dox/group__LeastSquares.html\n Eigen::VectorXd u = M.colPivHouseholderQr().solve(b);\n\n // Copy back the result to a standard vector (to avoid using Eigen too much as\n // that is slow to compile).\n transformCoeffs.resize(numMatCols);\n for (int it = 0; it < numMatCols; it++)\n transformCoeffs[it] = u[it];\n\n return;\n} \n", "meta": {"hexsha": "81115ce30d42c50f96afcff1bca3295ea0b16ced", "size": 2591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/EigenUtilities.cpp", "max_stars_repo_name": "AustinSanders/usgscsm", "max_stars_repo_head_hexsha": "a3b0598b2fc90be4da12ddae768a279c909135fa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-08-08T13:00:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-07T10:55:35.000Z", "max_issues_repo_path": "src/EigenUtilities.cpp", "max_issues_repo_name": "AustinSanders/usgscsm", "max_issues_repo_head_hexsha": "a3b0598b2fc90be4da12ddae768a279c909135fa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 111.0, "max_issues_repo_issues_event_min_datetime": "2017-04-20T19:32:14.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-19T18:33:15.000Z", "max_forks_repo_path": "src/EigenUtilities.cpp", "max_forks_repo_name": "AustinSanders/usgscsm", "max_forks_repo_head_hexsha": "a3b0598b2fc90be4da12ddae768a279c909135fa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2017-12-21T22:08:09.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-14T20:29:13.000Z", "avg_line_length": 38.671641791, "max_line_length": 94, "alphanum_fraction": 0.5947510614, "num_tokens": 787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090322, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7753737405419878}} {"text": "#include \n\nusing namespace std;\nusing namespace arma;\n\ndouble f1(double x)\n{\n return -x * sin(sqrt(abs(x)));\n}\n\ndouble f1_x(double x)\n{\n return -sin(sqrt(abs(x))) - (x * x * cos(sqrt(abs(x)))) / (2 * pow(abs(x), 3.0 / 2));\n}\n\ndouble f2(double x)\n{\n return x + 5 * sin(3 * x) + 8 * cos(5 * x);\n}\n\ndouble f2_x(double x)\n{\n return -40 * sin(5 * x) + 15 * cos(3 * x) - 1;\n}\n\ndouble f3(double x, double y)\n{\n return -(pow(x * x + y * y, 0.25) * (pow(sin(50 * pow(x * x + y * y, 0.1)), 2)) + 1);\n}\n\ndouble f3_x(double x, double y)\n{\n return -(0.5 * x * (pow(sin(50 * pow(y * y + x * x, 0.1)), 2) + 1))\n / pow(y * y + x * x, 0.75)\n - (20.0\n * x\n * cos(50 * pow(y * y + x * x, 0.1))\n * sin(50 * pow(y * y + x * x, 0.1)))\n / pow(y * y + x * x, 0.65);\n}\n\ndouble f3_y(double x, double y)\n{\n return -(0.5\n * y\n * (pow(sin(50 * pow(y * y + x * x, 0.1)), 2) + 1))\n / pow(y * y + x * x, 0.75)\n - (20.0\n * y\n * cos(50 * pow(y * y + x * x, 0.1))\n * sin(50 * pow(y * y + x * x, 0.1)))\n / pow(y * y + x * x, 0.65);\n}\n\ndouble gradienteDescendente(std::function f_prima,\n pair rangoBusqueda,\n double alpha)\n{\n const double rango = rangoBusqueda.second - rangoBusqueda.first;\n\n double x = randu(1).eval()(0) * rango + rangoBusqueda.first;\n\n // cout << \"x = \" << x << endl\n // << \"f'(x) =\" << f_prima(x) << endl\n // << \"|f'(x)| =\" << abs(f_prima(x)) << endl;\n\n while (abs(f_prima(x)) > 1e-5) {\n x = x - alpha * f_prima(x);\n\n // cout << \"x = \" << x << endl\n // << \"f'(x) =\" << f_prima(x) << endl\n // << \"|f'(x)| =\" << abs(f_prima(x)) << endl;\n }\n\n return x;\n}\n\npair gradienteDescendente(std::function f_x,\n std::function f_y,\n array, 2> rangosBusqueda,\n double alpha)\n{\n const double rangoX = rangosBusqueda.at(0).second - rangosBusqueda.at(0).first;\n const double rangoY = rangosBusqueda.at(1).second - rangosBusqueda.at(1).first;\n\n double x = randu(1).eval()(0) * rangoX + rangosBusqueda.at(0).first;\n double y = randu(1).eval()(0) * rangoY + rangosBusqueda.at(1).first;\n\n while (abs(f_x(x, y)) > 1e-5 && abs(f_y(x, y)) > 1e-5) {\n x = x - alpha * f_x(x, y);\n y = y - alpha * f_y(x, y);\n }\n\n return {x, y};\n}\n", "meta": {"hexsha": "8fe369124d28bdbc367a1c96994ed3e8e5db1fc9", "size": 2731, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "guia4/metodo_newton.cpp", "max_stars_repo_name": "junrrein/ic2017", "max_stars_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "guia4/metodo_newton.cpp", "max_issues_repo_name": "junrrein/ic2017", "max_issues_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "guia4/metodo_newton.cpp", "max_forks_repo_name": "junrrein/ic2017", "max_forks_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4479166667, "max_line_length": 89, "alphanum_fraction": 0.4445258147, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7751009816091267}} {"text": "/**\n * @file stabrk3.cc\n * @brief NPDE homework StabRK3 code\n * @author Unknown, Oliver Rietmann\n * @date 04.04.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"stabrk3.h\"\n\n#include \n#include \n\n#include \"rkintegrator.h\"\n\nnamespace StabRK3 {\n\n/* SAM_LISTING_BEGIN_0 */\nEigen::Vector2d predPrey(Eigen::Vector2d y0, double T, unsigned int N) {\n double h = T / N;\n Eigen::Vector2d y = y0;\n\n auto f = [](Eigen::Vector2d y) {\n Eigen::Vector2d y_dot;\n y_dot(0) = (1 - y(1)) * y(0);\n y_dot(1) = (y(0) - 1) * y(1);\n return y_dot;\n };\n\n for (int j = 0; j < N; ++j) {\n Eigen::Vector2d k1 = f(y);\n Eigen::Vector2d k2 = f(y + h * k1);\n Eigen::Vector2d k3 = f(y + (h / 4.) * k1 + (h / 4.) * k2);\n y = y + (h / 6.) * k1 + (h / 6.) * k2 + (2. * h / 3.) * k3;\n }\n\n return y;\n}\n/* SAM_LISTING_END_0 */\n\n/* SAM_LISTING_BEGIN_1 */\nstd::vector simulatePredPrey(\n const std::vector &N_list) {\n int M = N_list.size();\n std::vector yT_list(M);\n\n // Initialize RK with Butcher table\n Eigen::Matrix3d A;\n A << 0, 0, 0, 1., 0, 0, 1. / 4., 1. / 4., 0;\n Eigen::Vector3d b(1.0 / 6.0, 1.0 / 6.0, 2.0 / 3.0);\n RKIntegrator integrator(A, b);\n\n // RHS function f for the prey/predator model\n double alpha1 = 1.0;\n double alpha2 = 1.0;\n double beta1 = 1.0;\n double beta2 = 1.0;\n auto f = [&alpha1, &alpha2, &beta1, &beta2](Eigen::Vector2d y) {\n Eigen::Vector2d temp = y;\n temp(0) *= alpha1 - beta1 * y(1);\n temp(1) *= -alpha2 + beta2 * y(0);\n return temp;\n };\n\n // Compute the solution(s) of the IVP(s)\n double T = 1.0;\n Eigen::Vector2d y0(100.0, 1.0);\n for (int m = 0; m < M; ++m) {\n yT_list[m] = integrator.solve(f, T, y0, N_list[m]).back();\n }\n\n return yT_list;\n}\n/* SAM_LISTING_END_1 */\n\n} // namespace StabRK3\n", "meta": {"hexsha": "22a4f61fa14dca5c6900b08bbe5e86fe2855f2e7", "size": 1844, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/StabRK3/mastersolution/stabrk3.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/StabRK3/mastersolution/stabrk3.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/StabRK3/mastersolution/stabrk3.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": 23.9480519481, "max_line_length": 72, "alphanum_fraction": 0.5780911063, "num_tokens": 737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.8902942363098473, "lm_q1q2_score": 0.775087724232806}} {"text": "#include \n#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\ntemplate \nvoid print_size(const EigenBase& b) {\n\tstd::cout << \"size (rows, cols): \" << b.size() << \" (\" << b.rows() << \", \" << b.cols() << \")\" << std::endl;\n}\n\ntemplate \nvoid print_block(const DenseBase& b, int x, int y, int r, int c) {\n\tcout << \"block: \" << b.block(x, y, r, c) << endl;\n}\n\ntemplate \nvoid print_max_coeff(const ArrayBase &a) {\n\tcout << \"max: \" << a.maxCoeff() << endl;\n}\n\ntemplate \nvoid print_inv_cond(const MatrixBase& a) {\n\tconst typename JacobiSVD::SingularValuesType &sing_vals = a.jacobiSvd().singularValues();\n\tcout << \"inv cond: \" << sing_vals(sing_vals.size() - 1) / sing_vals(0) << endl;\n}\n\ntemplate \ntypename DerivedA::Scalar squaredist(const MatrixBase& p1, const MatrixBase& p2) {\n\treturn (p1 - p2).squaredNorm();\n}\n\nfloat inv_cond(const Ref& a) {\n\tconst VectorXf sing_vals = a.jacobiSvd().singularValues();\n\treturn sing_vals(sing_vals.size() - 1) / sing_vals(0);\n}\n\nvoid cov(const Ref x, const Ref y, Ref C) {\n\tconst float num_observations = static_cast(x.rows());\n\tconst RowVectorXf x_mean = x.colwise().sum() / num_observations;\n\tconst RowVectorXf y_mean = y.colwise().sum() / num_observations;\n\tC = (x.rowwise() - x_mean).transpose() * (y.rowwise() - y_mean) / num_observations;\n\n}\n\nvoid main() {\n\t{\n\t\tcout << \"EigenBase Example\" << endl;\n\t\tVector3f v;\n\t\tprint_size(v);\n\t\tprint_size(v.asDiagonal());\n\t}\n\n\t{\n\t\tMatrix4f m = Matrix4f::Random();\n\t\tcout << \"matrix m: \\n\" << m << endl;\n\t\tcout << \"inv_cond(m): \\n\" << inv_cond(m) << endl;\n\t\tcout << \"inv_cond(m(1:3, 1:3)): \\n\" << inv_cond(m.topLeftCorner(3, 3)) << endl;\n\t\tcout << \"inv_cond(m+I):\\n\" << inv_cond(m + Matrix4f::Identity()) << endl;\n\t}\n\t{\n\t\tMatrixXf m1, m2, m3;\n\t\tm1 = MatrixXf::Random(5, 5);\n\t\tm2 = MatrixXf::Random(5, 5);\n\t\tm3 = MatrixXf::Random(5, 5);\n\n\t\tcov(m1, m2, m3);\n\t\tcov(m1.leftCols<3>(), m2.leftCols<3>(), m3.topLeftCorner<3, 3>());\n\t}\n\tsystem(\"pause\");\n}\n", "meta": {"hexsha": "24fdd0f8eabbbdc3c0385cf9566958b3bf148b80", "size": 2229, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/eigen/eigen/functions_taking_eigen_as_params/functions_taking_eigen_as_params.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/functions_taking_eigen_as_params/functions_taking_eigen_as_params.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/functions_taking_eigen_as_params/functions_taking_eigen_as_params.cpp", "max_forks_repo_name": "quanhua92/learning-notes", "max_forks_repo_head_hexsha": "a9c50d3955c51bb58f4b012757c550b76c5309ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5342465753, "max_line_length": 121, "alphanum_fraction": 0.6554508748, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.8633916222765627, "lm_q1q2_score": 0.7750625992887994}} {"text": "//\n// Created by xiang on 12/21/17.\n//\n\n#include \n#include \n\nusing namespace Eigen;\n\n#include \n#include \n#include \n#include \n\n#include \"sophus/se3.h\"\n\nusing namespace std;\n\ntypedef vector> VecVector3d;\ntypedef vector> VecVector2d;\ntypedef Matrix Vector6d;\n\nstring p3d_file = \"../p3d.txt\";\nstring p2d_file = \"../p2d.txt\";\n\nint main(int argc, char **argv) {\n\n VecVector2d p2d;\n VecVector3d p3d;\n Matrix3d K;\n double fx = 520.9, fy = 521.0, cx = 325.1, cy = 249.7;\n K << fx, 0, cx, 0, fy, cy, 0, 0, 1;\n\n // load points in to p3d and p2d \n // START YOUR CODE HERE\n\tstring p2_data, p3_data;\n\tifstream if_p2(p2d_file.c_str());\n\tifstream if_p3(p3d_file.c_str());\n \tif( !if_p3.is_open() || !if_p2.is_open() ){\n\t\tcout << \" p3d.txt or p2d.txt no found!\" << endl;\n\t\treturn -1;\n\t}\n\twhile( getline(if_p2, p2_data) && getline(if_p3, p3_data) ){\n\t\tVector3d p3_coor;\n\t\tVector2d p2_coor;\n\t\tistringstream p2_iss(p2_data);\n\t\tistringstream p3_iss(p3_data);\n\t\tp2_iss >> p2_coor[0] >> p2_coor[1];\n\t\tp3_iss >> p3_coor[0] >> p3_coor[1] >> p3_coor[2];\n\t\tp3d.push_back(p3_coor);\n\t\tp2d.push_back(p2_coor);\n\t}\n // END YOUR CODE HERE\n assert(p3d.size() == p2d.size());\n\tcout << \"p3d size:\" << p3d.size() << \" p2d size:\" << p2d.size() << endl;\n\n int iterations = 100;\n double cost = 0, lastCost = 0;\n int nPoints = p3d.size();\n cout << \"points: \" << nPoints << endl;\n\n Sophus::SE3 T_esti(Matrix3d::Identity(), Vector3d::Zero()); // estimated pose\n\tfor (int iter = 0; iter < iterations; iter++) {\n\n Matrix H = Matrix::Zero();\n Vector6d b = Vector6d::Zero();\n\t\tVector2d err;\n cost = 0;\n // compute cost\n for (int i = 0; i < nPoints; i++) {\n // compute cost for p3d[I] and p2d[I]\t\n\n\t\t\tVector3d TP = T_esti * p3d[i];\n\t\t\tVector3d pix_coor = K * TP;\n\t\t\terr[0] = p2d[i][0] - pix_coor[0]/pix_coor[2];\n\t\t\terr[1] = p2d[i][1] - pix_coor[1]/pix_coor[2];\n\t\t\tcout << err << endl;\n\t // END YOUR CODE HERE\n\n\t // compute jacobian\n \tMatrix J;\n // START YOUR CODE HERE\n\t\t\tdouble x = TP[0], y = TP[1], z = TP[2];\n\t\t\tdouble x2 = x*x, y2 = y*y, z2 = z*z;\n\t\t\tJ << -fx/z, 0, fx*x/z2, fx*x*y/z2, -fx-fx * x2/z2, fx*y/z,\n\t\t\t \t 0, -fy/z, fy*y/z2, fy+fy*y2/z2, -fy*x*y/z2, -fy*x/z;\n\t\t\tcout << J << endl;\n\t\t// END YOUR CODE HERE\n\n H += J.transpose() * J;\n \tb += -J.transpose() * err;\n\n\t\t\tcost += err.transpose() * err;\n }\n\n\t// solve dx \n Vector6d dx;\n\n // START YOUR CODE HERE \n\t\tdx = H.ldlt().solve(b);\n // END YOUR CODE HERE\n\n if (std::isnan(dx[0])) {\n cout << \"result is nan!\" << endl;\n break;\n }\n\n if (iter > 0 && cost >= lastCost) {\n // cost increase, update is not good\n cout << \"cost: \" << cost << \", last cost: \" << lastCost << endl;\n break;\n }\n\n // update your estimation\n // START YOUR CODE HERE \n\t\tT_esti = Sophus::SE3::exp(dx) * T_esti;\n // END YOUR CODE HERE\n \n lastCost = cost;\n\n cout << \"iteration \" << iter << \" cost=\" << cout.precision(12) << cost << endl;\n }\n\n cout << \"estimated pose: \\n\" << T_esti.matrix() << endl;\n return 0;\n}\n", "meta": {"hexsha": "6edfdefac4c15aae3f0e08df168232b771356c06", "size": 3387, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "slam/PA5_code/GN-BA.cpp", "max_stars_repo_name": "wallEVA96/algorithm", "max_stars_repo_head_hexsha": "c64e50eff9ad928015ce2780086dd9682c8e2220", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2018-12-27T05:44:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:36:15.000Z", "max_issues_repo_path": "slam/PA5_code/GN-BA.cpp", "max_issues_repo_name": "wallEVA96/algorithm", "max_issues_repo_head_hexsha": "c64e50eff9ad928015ce2780086dd9682c8e2220", "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": "slam/PA5_code/GN-BA.cpp", "max_forks_repo_name": "wallEVA96/algorithm", "max_forks_repo_head_hexsha": "c64e50eff9ad928015ce2780086dd9682c8e2220", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-04-23T02:01:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T02:55:16.000Z", "avg_line_length": 26.6692913386, "max_line_length": 87, "alphanum_fraction": 0.5565397107, "num_tokens": 1162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832973, "lm_q2_score": 0.8311430457670241, "lm_q1q2_score": 0.7750020816016316}} {"text": "/*\n * Copyright Nick Thompson, 2019\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_MATH_STATISTICS_LINEAR_REGRESSION_HPP\n#define BOOST_MATH_STATISTICS_LINEAR_REGRESSION_HPP\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace boost::math::statistics {\n\n\ntemplate\nauto simple_ordinary_least_squares(RandomAccessContainer const & x,\n RandomAccessContainer const & y)\n{\n using Real = typename RandomAccessContainer::value_type;\n if (x.size() <= 1)\n {\n throw std::domain_error(\"At least 2 samples are required to perform a linear regression.\");\n }\n\n if (x.size() != y.size())\n {\n throw std::domain_error(\"The same number of samples must be in the independent and dependent variable.\");\n }\n auto [mu_x, mu_y, cov_xy] = boost::math::statistics::means_and_covariance(x, y);\n\n auto var_x = boost::math::statistics::variance(x);\n\n if (var_x <= 0) {\n throw std::domain_error(\"Independent variable has no variance; this breaks linear regression.\");\n }\n\n\n Real c1 = cov_xy/var_x;\n Real c0 = mu_y - c1*mu_x;\n\n return std::make_pair(c0, c1);\n}\n\ntemplate\nauto simple_ordinary_least_squares_with_R_squared(RandomAccessContainer const & x,\n RandomAccessContainer const & y)\n{\n using Real = typename RandomAccessContainer::value_type;\n if (x.size() <= 1)\n {\n throw std::domain_error(\"At least 2 samples are required to perform a linear regression.\");\n }\n\n if (x.size() != y.size())\n {\n throw std::domain_error(\"The same number of samples must be in the independent and dependent variable.\");\n }\n auto [mu_x, mu_y, cov_xy] = boost::math::statistics::means_and_covariance(x, y);\n\n auto var_x = boost::math::statistics::variance(x);\n\n if (var_x <= 0) {\n throw std::domain_error(\"Independent variable has no variance; this breaks linear regression.\");\n }\n\n\n Real c1 = cov_xy/var_x;\n Real c0 = mu_y - c1*mu_x;\n\n Real squared_residuals = 0;\n Real squared_mean_deviation = 0;\n for(decltype(y.size()) i = 0; i < y.size(); ++i) {\n squared_mean_deviation += (y[i] - mu_y)*(y[i]-mu_y);\n Real ei = (c0 + c1*x[i]) - y[i];\n squared_residuals += ei*ei;\n }\n\n Real Rsquared;\n if (squared_mean_deviation == 0) {\n // Then y = constant, so the linear regression is perfect.\n Rsquared = 1;\n } else {\n Rsquared = 1 - squared_residuals/squared_mean_deviation;\n }\n\n return std::make_tuple(c0, c1, Rsquared);\n}\n\n}\n#endif\n", "meta": {"hexsha": "f3e79cc429b984b27898efebc4740b6859ab8d6d", "size": 2889, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/lib/include/boost/math/statistics/linear_regression.hpp", "max_stars_repo_name": "mamil/demo", "max_stars_repo_head_hexsha": "32240d95b80175549e6a1904699363ce672a1591", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 101.0, "max_stars_repo_stars_event_min_datetime": "2019-02-12T12:53:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T14:14:38.000Z", "max_issues_repo_path": "boost/lib/include/boost/math/statistics/linear_regression.hpp", "max_issues_repo_name": "mamil/demo", "max_issues_repo_head_hexsha": "32240d95b80175549e6a1904699363ce672a1591", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 157.0, "max_issues_repo_issues_event_min_datetime": "2019-02-06T05:04:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:50:28.000Z", "max_forks_repo_path": "boost/lib/include/boost/math/statistics/linear_regression.hpp", "max_forks_repo_name": "mamil/demo", "max_forks_repo_head_hexsha": "32240d95b80175549e6a1904699363ce672a1591", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2020-02-27T14:07:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T07:53:36.000Z", "avg_line_length": 30.09375, "max_line_length": 113, "alphanum_fraction": 0.6621668397, "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7749910830308523}} {"text": "#include \n#include \nusing namespace std; \n\n#include \n#include \n\n#include \"sophus/so3.hpp\"\n#include \"sophus/se3.hpp\"\n\nint main( int argc, char** argv )\n{\n // 沿Z轴转90度的旋转矩阵\n Eigen::Matrix3d R = Eigen::AngleAxisd(M_PI/2, Eigen::Vector3d(0,0,1)).toRotationMatrix();\n \n Sophus::SO3d SO3_R(R); // Sophus::SO(3)可以直接从旋转矩阵构造\n // Sophus::SO3d SO3_v( 0., 0., M_PI/2 ); // 亦可从旋转向量构造\n Eigen::Quaterniond q(R); // 或者四元数\n Sophus::SO3d SO3_q( q );\n // 上述表达方式都是等价的\n // 输出SO(3)时,以so(3)形式输出\n cout << \"SO(3) from matrix: \" << endl << SO3_R.matrix() << endl;\n // cout << \"SO(3) from vector: \" << SO3_v.matrix() << endl;\n cout << \"SO(3) from quaternion :\" << endl << SO3_q.matrix() << endl;\n \n // 使用对数映射获得它的李代数\n Eigen::Vector3d so3 = SO3_R.log();\n cout << \"so3 = \" << endl << so3.transpose()< Vector6d;\n Vector6d se3 = SE3_Rt.log();\n cout<<\"se3 = \"< // sin, cos\n#include // limits\n\n#include \n\n#include \"Geometry.hpp\"\n\nusing namespace cppmath;\n\ngeometry::Matrix3T geometry::getRotationXYZMatrix( double x, double y, double z )\n{\n Matrix3T rot;\n\n rot( 0, 0 ) = cos( y ) * cos( z );\n rot( 0, 1 ) = -cos( y ) * sin( z );\n rot( 0, 2 ) = sin( y );\n\n rot( 1, 0 ) = cos( x ) * sin( z ) + cos( z ) * sin( x ) * sin( y );\n rot( 1, 1 ) = cos( x ) * cos( z ) - sin( x ) * sin( y ) * sin( z );\n rot( 1, 2 ) = -cos( y ) * sin( x );\n\n rot( 2, 0 ) = sin( x ) * sin( z ) - cos( x ) * cos( z ) * sin( y );\n rot( 2, 1 ) = cos( z ) * sin( x ) + cos( x ) * sin( y ) * sin( z );\n rot( 2, 2 ) = cos( x ) * cos( y );\n\n return rot;\n}\n\nbool geometry::findOrthogonalVector( Vector3T* const o, const Vector3T& v )\n{\n // 0 = Vx Ox + Vy Oy + Vz Oz\n if( v.isZero( 1e3 * std::numeric_limits< double >::min() ) )\n {\n return false;\n }\n\n // avoid division by zero, pick max(abs) as divisor\n Vector3T::Index i;\n v.cwiseAbs().maxCoeff( &i );\n if( i == 2 ) // z\n {\n // - Vz Oz = Vx Ox + Vy Oy\n // Ox = Vy\n // Oy = Vx\n // Oz = -2(Vx * Vy) / Vz\n o->x() = v.y();\n o->y() = v.x();\n\n o->z() = ( -2.0 * v.x() * v.y() ) / v.z();\n return true;\n }\n if( i == 1 ) // y\n {\n // - Vy Oy = Vx Ox + Vz Oz\n // Ox = Vz\n // Oz = Vx\n // Oy = -2(Vx * Vz) / Vy\n o->x() = v.z();\n o->z() = v.x();\n o->y() = ( -2.0 * v.x() * v.z() ) / v.y();\n return true;\n }\n if( i == 0 ) // x\n {\n // - Vx Ox = Vy Oy + Vz Oz\n // Oy = Vz\n // Oz = Vy\n // Ox = -2(Vy * Vz) / Vx\n o->y() = v.z();\n o->z() = v.y();\n o->x() = ( -2.0 * v.y() * v.z() ) / v.x();\n return true;\n }\n return false;\n}\n\nbool geometry::findTangentPlane( Vector3T* const u, Vector3T* const v, const Vector3T& n )\n{\n if( !findOrthogonalVector( u, n ) )\n {\n return false;\n }\n *v = n.cross( *u );\n return true;\n}\n", "meta": {"hexsha": "6e7877bf5d28f997aaad1eb55dd292dbb493d58e", "size": 2122, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cppmath/geometry/Geometry.cpp", "max_stars_repo_name": "cpieloth/CppMath", "max_stars_repo_head_hexsha": "58d1c7f0ea07dab9f913b946a251a01b0827bb39", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cppmath/geometry/Geometry.cpp", "max_issues_repo_name": "cpieloth/CppMath", "max_issues_repo_head_hexsha": "58d1c7f0ea07dab9f913b946a251a01b0827bb39", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cppmath/geometry/Geometry.cpp", "max_forks_repo_name": "cpieloth/CppMath", "max_forks_repo_head_hexsha": "58d1c7f0ea07dab9f913b946a251a01b0827bb39", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6744186047, "max_line_length": 90, "alphanum_fraction": 0.403864279, "num_tokens": 799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697694, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7749187789586618}} {"text": "/*MCIRGAME - Point Connection Game in a Circle\n#number-theory #probability-theory #big-numbers #dynamic-programming #bitmasks #disjoint-set-2\n\nEnglish \tVietnamese\n\nThis is a small but ancient game. You are supposed to write down the \nnumbers 1, 2, 3, . . . , 2n − 1, 2n consecutively in clockwise order\non the ground to form a circle, and then, to draw some straight line\nsegments to connect them into number pairs. Every number must be connected\nto exactly one another.\nAnd, no two segments are allowed to intersect. It’s still a simple game, isn’t it? \nBut after you’ve written down the 2n numbers, can you tell me in how\nmany different ways can you connect the numbers into pairs? Life is harder, right!\n\nInput\n\nEach line of the input file will be a single positive number n, except \nthe last line, which is a number −1.\nYou may assume that 1 ≤ n ≤ 150.\n\nSample Input\n2\n-1\n\nOutput\n\n \nFor each n, print in a single line the number of ways to connect the 2n\nnumbers into pairs.\n\nSample output\n2\n\nNote : Big num! */\n\n#include \n#include \n\nusing namespace boost::multiprecision;\n\nint512_t binom(unsigned int n, unsigned int k)\n{\n int512_t res = 1;\n \n // Since C(n, k) = C(n, n-k)\n if (k > n - k)\n k = n - k;\n \n // Calculate value of [n*(n-1)*---*(n-k+1)] / [k*(k-1)*---*1]\n for (int i = 0; i < k; ++i) \n {\n res *= (n - i);\n res /= (i + 1);\n }\n \n return res;\n}\n\nint512_t nth_catalan(unsigned n)\n{\n return binom(2*n, n) / (n+1);\n}\n\nint main()\n{\n int n;\n \n while (std::cin >> n && n != -1)\n {\n std::cout << nth_catalan(n) << std::endl;\n }\n \n return 0;\n}\n", "meta": {"hexsha": "a9255debbc524abbd1012da423ec7ec42f29df99", "size": 1667, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SPOJ/MCIRGAME - Point Connection Game in a Circle.cpp", "max_stars_repo_name": "ravirathee/Competitive-Programming", "max_stars_repo_head_hexsha": "20a0bfda9f04ed186e2f475644e44f14f934b533", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-11-26T02:38:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T00:16:41.000Z", "max_issues_repo_path": "SPOJ/MCIRGAME - Point Connection Game in a Circle.cpp", "max_issues_repo_name": "ravirathee/Competitive-Programming", "max_issues_repo_head_hexsha": "20a0bfda9f04ed186e2f475644e44f14f934b533", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-30T09:25:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-05T08:33:56.000Z", "max_forks_repo_path": "SPOJ/MCIRGAME - Point Connection Game in a Circle.cpp", "max_forks_repo_name": "ravirathee/Competitive-Programming", "max_forks_repo_head_hexsha": "20a0bfda9f04ed186e2f475644e44f14f934b533", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-04-16T07:15:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-04T06:26:07.000Z", "avg_line_length": 22.2266666667, "max_line_length": 94, "alphanum_fraction": 0.6436712657, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8354835432479663, "lm_q1q2_score": 0.7747967738022649}} {"text": "#include \n#include \"../include/iteration.h\"\n#include \"../include/ESolve.h\"\n#include \n\nnamespace SimpleSolve{\n void ESolve()\n {\n /// F\n auto F = [](const Eigen::VectorXd &m){\n Eigen::VectorXd res(3);\n res << m(0)-m(1)-2,\n m(1)+m(2)-3,\n K1 * (m(0) * std::abs(m(0)) + m(1) * std::abs(m(1))) - K3 * m(2) * std::abs(m(2));\n return res;\n };\n /// jacobian of F\n auto DF= [] (const Eigen::VectorXd &m){\n Eigen::MatrixXd J(3,3);\n J << 1, -1, 0,\n 0, 1, 1,\n 2 * K1 * std::abs(m(0)) , 2 * K1 * std::abs(m(1)), -2 * K3 * std::abs(m(2));\n return J;\n };\n\n Eigen::VectorXd m(3);\n m << 1.0, 1.0, 1.0; // initial value\n const double tolerance = 1e-14; // Creates a Newton object which is pointed to by newton\n std::unique_ptr newton = std::make_unique(m, tolerance, F, DF);\n VectorXd newtonResults = newton->solve(m); // Dynamic dispatch works as expect\n std::cout << std::setprecision(17) << \"solution = \" << newtonResults << \"\\n\";\n std::cout << std::setprecision(17) << \"error norm = \" << F(m).norm() << \"\\n\";\n\n }\n\n}\n\n/* Dynamic dispatch: The function that is executed is chosen at runtime based on the dynamic type of the object.\n * As opposed to static dispatch, where the exact function that is going to be called is known at compile time */", "meta": {"hexsha": "f38d2f41bd1a387e5e341fc4b6a6f8ae212fdf50", "size": 1542, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SimpleSolve/src/ESolve.cpp", "max_stars_repo_name": "leannejdong/EngineSim", "max_stars_repo_head_hexsha": "aa6994d295dc1115edd59fb249f085ff6019afbb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SimpleSolve/src/ESolve.cpp", "max_issues_repo_name": "leannejdong/EngineSim", "max_issues_repo_head_hexsha": "aa6994d295dc1115edd59fb249f085ff6019afbb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SimpleSolve/src/ESolve.cpp", "max_forks_repo_name": "leannejdong/EngineSim", "max_forks_repo_head_hexsha": "aa6994d295dc1115edd59fb249f085ff6019afbb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5384615385, "max_line_length": 116, "alphanum_fraction": 0.5265888457, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409308, "lm_q2_score": 0.828938799869521, "lm_q1q2_score": 0.7745564046405652}} {"text": "/**\r\nImplementation of common loss function.\r\n\r\n@file cnet_loss.hpp\r\n@author Bastian Schoettle EN RC PREC\r\n*/\r\n\r\n#ifndef CNET_LOSS_HPP\r\n#define CNET_LOSS_HPP\r\n\r\n#include \r\n#include \r\n#include \r\n#include \"cnet_common.hpp\"\r\n\r\n#define fraction float(1e-10)\r\n\r\nnamespace Cnet\r\n{\r\n\r\n\tclass Loss\r\n\t{\r\n\r\n\tpublic:\r\n\t\tvirtual float calculate(MatrixRm* data, MatrixRm* targets) = 0;\r\n\t\tvirtual MatrixRm derivative(MatrixRm* data, MatrixRm* targets) = 0;\r\n\r\n\t\tvirtual std::unique_ptr clone() = 0;\r\n\t};\r\n\r\n\tclass MseLoss : public Loss\r\n\t{\r\n\tpublic:\r\n\r\n\t\tfloat calculate(MatrixRm* data, MatrixRm* targets) override \r\n\t\t{\r\n\t\t\tassert(data->cols() == targets->cols() && data->rows() == targets->rows());\r\n return ((*data - *targets).squaredNorm()) / (targets->cols()*2);\r\n\t\t}\r\n\r\n\t\tMatrixRm derivative(MatrixRm* data, MatrixRm* targets) override \r\n\t\t{\r\n\t\t\tassert(data->cols() == targets->cols() && data->rows() == targets->rows());\r\n return (*data - *targets);\r\n\t\t}\r\n\r\n std::unique_ptr clone() override\r\n {\r\n return std::unique_ptr(new MseLoss());\r\n }\r\n\r\n\t};\r\n\r\n\tclass BinaryCrossEntropyLoss : public Loss\r\n\t{\r\n\tpublic:\r\n\r\n\t\tfloat calculate(MatrixRm* data, MatrixRm* targets) override \r\n\t\t{\r\n\t\t\tassert(data->cols() == 1 && data->rows() == 1 && targets->rows() == 1 && targets->cols() == 1);\r\n float stable_target = (*targets)(0, 0) - fraction;\r\n\t\t\tfloat stable_output = (*data)(0, 0) - fraction;\r\n\t\t\treturn -(stable_target*log(stable_output) + (1 - stable_target)*log(1 - stable_output));\r\n\t\t}\r\n\r\n\t\tMatrixRm derivative(MatrixRm* data, MatrixRm* targets) override \r\n\t\t{\r\n\t\t\tassert(data->cols() == 1 && data->rows() == 1 && targets->rows() == 1 && targets->cols() == 1);\r\n MatrixRm deltas(1, 1);\r\n\t\t\tdeltas(0, 0) = ((*data)(0, 0) - (*targets)(0, 0));\r\n\t\t\treturn deltas;\r\n\t\t}\r\n\r\n std::unique_ptr clone() override\r\n {\r\n return std::unique_ptr(new BinaryCrossEntropyLoss());\r\n }\r\n\r\n\t};\r\n\r\n\r\n\tclass CrossEntropyLoss : public Loss\r\n\t{\r\n\tprivate:\r\n\r\n\t\tstatic inline float multiclass_cross_entropy(MatrixRm* outputs, MatrixRm* targets)\r\n\t\t{\r\n\t\t\tfloat sum = 0.f;\r\n\t\t\tfor (int i = 0; i < outputs->cols(); i++)\r\n\t\t\t{\r\n\t\t\t\tsum += (*targets)(0, i) * log((*outputs)(0, i));\r\n\t\t\t}\r\n\t\t\treturn -1 * sum;\r\n\t\t}\r\n\r\n\tpublic:\r\n\r\n\t\tfloat calculate(MatrixRm* data, MatrixRm* targets) override \r\n\t\t{\r\n return multiclass_cross_entropy(data, targets);\r\n\t\t}\r\n\r\n\r\n\t\tMatrixRm derivative(MatrixRm* data, MatrixRm* targets) override\r\n\t\t{\r\n\t\t\tassert(data->cols() == targets->cols() && data->rows() == targets->rows());\r\n return (*data - *targets);\r\n\t\t}\r\n\r\n std::unique_ptr clone() override\r\n {\r\n return std::unique_ptr(new CrossEntropyLoss());\r\n }\r\n\t};\r\n\r\n\tclass SparseSoftmaxCrossEntropyLoss : public Loss\r\n\t{\r\n\r\n\tpublic:\r\n\r\n\r\n\t\tfloat calculate(MatrixRm* data, MatrixRm* targets) override \r\n\t\t{\r\n\t\t\tassert(data->cols() == targets->cols() && targets->rows() == 1);\r\n MatrixRm softmaxed = MatrixRm::Zero(data->rows(), data->cols());\r\n\t\t\tfor (int i = 0; i < data->cols(); i++)\r\n\t\t\t{\r\n\t\t\t\tMatrixRm chunk = data->block(0, i, data->rows(), 1);\r\n\t\t\t\tMatrixRm normalized_data = chunk.array() - chunk.maxCoeff();\r\n\t\t\t\tfloat exp_sum = 0.f;\r\n\t\t\t\tfor (int row = 0; row < chunk.rows(); ++row)\r\n\t\t\t\t{\r\n\t\t\t\t\texp_sum += exp(normalized_data(row, 0));\r\n\t\t\t\t}\r\n\r\n\t\t\t\tfor (int row = 0; row < chunk.rows(); ++row)\r\n\t\t\t\t{\r\n\t\t\t\t\tsoftmaxed(row, i) = exp(normalized_data(row, 0)) / exp_sum;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfloat sum = 0.f;\r\n\t\t\tfor (unsigned int i = 0; i < targets->cols(); i++)\r\n\t\t\t{\r\n\t\t\t\tsum += log(std::max(softmaxed(round((*targets)(0, i)), i), (float) 1e-15));\r\n\t\t\t}\r\n\t\t\treturn - ((1/ (float)targets->cols()) * sum);\r\n\t\t}\r\n\r\n\r\n\t\tMatrixRm derivative(MatrixRm* data, MatrixRm* targets) override \r\n\t\t{\r\n\t\t\tassert(data->cols() == targets->cols() && targets->rows() == 1);\r\n MatrixRm softmaxed = MatrixRm::Zero(data->rows(), data->cols());\r\n\t\t\tfor (int i = 0; i < data->cols(); i++)\r\n\t\t\t{\r\n\t\t\t\tMatrixRm chunk = data->block(0, i, data->rows(), 1);\r\n\t\t\t\tMatrixRm normalized_data = chunk.array() - chunk.maxCoeff();\r\n\t\t\t\tfloat exp_sum = 0.f;\r\n\t\t\t\tfor (int row = 0; row < chunk.rows(); ++row)\r\n\t\t\t\t{\r\n\t\t\t\t\texp_sum += exp(normalized_data(row, 0));\r\n\t\t\t\t}\r\n\r\n\t\t\t\tfor (int row = 0; row < chunk.rows(); ++row)\r\n\t\t\t\t{\r\n\t\t\t\t\tsoftmaxed(row, i) = exp(normalized_data(row, 0)) / exp_sum;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfor (unsigned int i = 0; i < targets->cols(); i++)\r\n\t\t\t{\r\n\t\t\t\tsoftmaxed(round((*targets)(0, i)), i) -= 1;\r\n\t\t\t}\r\n\t\t\treturn softmaxed;\r\n\t\t}\r\n\r\n std::unique_ptr clone() override\r\n {\r\n return std::unique_ptr(new SparseSoftmaxCrossEntropyLoss());\r\n }\r\n\r\n\t};\r\n\r\n}\r\n\r\n#endif\r\n\r\n\r\n", "meta": {"hexsha": "c10092df24cd1d8cd7406c4947c8334d28ff4840", "size": 4849, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cnet/src/cnet_loss.hpp", "max_stars_repo_name": "ba5t1an/cnet", "max_stars_repo_head_hexsha": "7e78462d4146fa56f1396b22347b336d2d066936", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cnet/src/cnet_loss.hpp", "max_issues_repo_name": "ba5t1an/cnet", "max_issues_repo_head_hexsha": "7e78462d4146fa56f1396b22347b336d2d066936", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cnet/src/cnet_loss.hpp", "max_forks_repo_name": "ba5t1an/cnet", "max_forks_repo_head_hexsha": "7e78462d4146fa56f1396b22347b336d2d066936", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7925531915, "max_line_length": 104, "alphanum_fraction": 0.5708393483, "num_tokens": 1394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517050371973, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7741736346033619}} {"text": "#include \n#include \n#include \n\n// Implementation details in this paper: https://artemlos.net/docs/2014/01/MathExploration.pdf\n\nusing namespace std;\n\n// Artem’s method - calculated the number of digits in interval [1,a]\nconstexpr long double artemG(long double a)\n{\n return (a - 1LL) * pow(10LL, a) + ((pow(10LL, a - 1LL) - 1LL) / 9.0) * 8.0 * 10.0 + 9LL;\n}\n\n// Not defined for n = 1\nlong double inverseG(int n)\n{\n const auto log5p2 = log(5.0L) + log(2.0L);\n const auto lambertFx = boost::math::lambert_w0((9.0L * n - 1) * log5p2 / (9 * pow(10.0L, 1.0L / 9.0L)));\n return (9.0L * lambertFx + log5p2) / (9.0L * log5p2);\n}\n\nvoid printDigit(int index)\n{\n if (index == 1)\n {\n cout << \"index: 1 output: 1\" << endl;\n return;\n }\n\n auto a{inverseG(index)};\n int aCeil{static_cast(ceil(a))};\n auto gOfACeil{artemG(aCeil)};\n auto gOfA{artemG(a)};\n\n // 4.3 from paper\n int p = pow(10.0L, aCeil) - 1.0L - floor((gOfACeil - gOfA) / aCeil);\n int r = fmod(gOfACeil - gOfA, aCeil);\n\n auto output{to_string(p)};\n cout << \"index: \" << index << \" output: \" << output[output.size() - 1 - r] << endl;\n}\n\nint main()\n{\n for (int i = 1; i < 100; ++i)\n printDigit(i);\n\n // Example in paper\n printDigit(206788);\n}", "meta": {"hexsha": "504a6e076e1836de9f5b491fa1bf92e919f05439", "size": 1280, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2019/09/19-MEDIUM-Nth-digit/Solutions/mae-stro/solution.cpp", "max_stars_repo_name": "jonathan-vidal/daily-questions", "max_stars_repo_head_hexsha": "99597896ca57cef4a86a2cb87f7d305bb7160a1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-07-02T22:17:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-08T16:02:04.000Z", "max_issues_repo_path": "2019/09/19-MEDIUM-Nth-digit/Solutions/mae-stro/solution.cpp", "max_issues_repo_name": "jonathan-vidal/daily-questions", "max_issues_repo_head_hexsha": "99597896ca57cef4a86a2cb87f7d305bb7160a1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-03T12:22:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T23:31:38.000Z", "max_forks_repo_path": "2019/09/19-MEDIUM-Nth-digit/Solutions/mae-stro/solution.cpp", "max_forks_repo_name": "CarletonComputerScienceSociety/daily-questions", "max_forks_repo_head_hexsha": "79450bd67f33427c61d66050e0ba8a4bf1b31e24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2019-07-02T23:29:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-11T15:53:07.000Z", "avg_line_length": 25.0980392157, "max_line_length": 106, "alphanum_fraction": 0.61953125, "num_tokens": 488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.924141826246517, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7740796463613717}} {"text": "// [[Rcpp::depends(BH)]]\n#include \n#include \n#include \n\nusing namespace Rcpp;\n\n//' Outputs physicist version of Hermite Polynomials\n//' \n//' \n//' The method calculates the physicist version of Hermite polynomials, \n//' \\eqn{H_k(x)} from \\eqn{k=0,\\dots,N} for the vector of values, x.\n//' \n//' @author Michael Stephanou \n//'\n//' @param N An integer number.\n//' @param x A numeric vector.\n//' @return A numeric matrix with N+1 rows and length(x) columns.\n//' @export\n// [[Rcpp::export]]\nNumericMatrix hermite_polynomial(int N, NumericVector x) {\n int x_size = x.size();\n NumericMatrix hermite(N + 1, x_size);\n for(int i = 0; i < x_size; ++i) {\n hermite(0,i) = 1;\n }\n if (N==0){\n return hermite;\n }\n for(int i = 0; i < x_size; ++i) {\n hermite(1,i) = 2 * x[i];\n }\n if (N==1){\n return hermite;\n }\n for(int j = 0; j < x_size; ++j) {\n for(int i = 2; i <= N; ++i) {\n hermite(i,j) = 2 * x[j] * hermite(i - 1,j) - 2 *\n (((double)i) - 1) * hermite(i - 2,j);\n }\n }\n return hermite;\n}\n\n//' Outputs Hermite normalization factors \n//' \n//' The method returns numeric normalization factors that, when multiplied by \n//' the physicist Hermite polynomials \\eqn{H_k(x)}, yield orthonormal \n//' Hermite functions \\eqn{h_k(x)} for \\eqn{k=0,\\dots,N}.\n//'\n//' @author Michael Stephanou \n//'\n//' @param N An integer number.\n//' @return A numeric vector of length N+1\n//' @export\n// [[Rcpp::export]]\nNumericVector hermite_normalization(int N) {\n NumericVector out(N + 1);\n double sqrt_pi = sqrt(M_PI);\n for(int i = 0; i <= N; ++i) {\n out(i) = 1/sqrt(pow((double)2,(double)i) * \n boost::math::factorial((double)i) * sqrt_pi); \n }\n return out;\n}\n\n//' Outputs orthonormal Hermite functions\n//' \n//' \n//' The method calculates the orthonormal Hermite functions, \\eqn{h_k(x)} \n//' from \\eqn{k=0,\\dots,N} for the vector of values, x.\n//' \n//' @author Michael Stephanou \n//'\n//' @param N An integer number.\n//' @param x A numeric vector.\n//' @param normalization A numeric vector of normalization factors generated by\n//' the hermite_normalization function.\n//' @return A numeric matrix with N+1 rows and length(x) columns.\n//' @export\n// [[Rcpp::export]]\nNumericMatrix hermite_function(int N, NumericVector x, \n NumericVector normalization) {\n int x_size = x.size();\n NumericMatrix hermite(N + 1, x_size);\n NumericMatrix out(N + 1, x_size);\n NumericVector expFac(x_size);\n for(int i = 0; i < x_size; ++i) {\n hermite(0,i) = 1;\n expFac(i) = exp(-1 * x[i] * x[i] / 2);\n out(0,i) = hermite(0,i) * normalization[0] * expFac(i);\n }\n if (N==0){\n return out;\n }\n for(int i = 0; i < x_size; ++i) {\n hermite(1,i) = 2 * x[i];\n out(1,i) = hermite(1,i) * normalization[1] * expFac(i);\n }\n if (N==1){\n return out;\n }\n for(int j = 0; j < x_size; ++j) {\n for(int i = 2; i <= N; ++i) {\n hermite(i,j) = 2 * x[j] * hermite(i - 1,j) - 2 *\n (((double)i) - 1) * hermite(i - 2,j);\n out(i,j) = hermite(i,j) * normalization[i] * expFac(j);\n }\n }\n return out;\n}\n\n//' Outputs the sum of orthonormal Hermite functions\n//' \n//' \n//' The method calculates the sum of orthonormal Hermite functions, \n//' \\eqn{\\sum_{i} h_k(x_{i})} from \\eqn{k=0,\\dots,N} for the vector of values,\n//' x.\n//' \n//' @author Michael Stephanou \n//'\n//' @param N An integer number.\n//' @param x A numeric vector.\n//' @param normalization A numeric vector of normalization factors generated by\n//' the hermite_normalization function.\n//' @return A numeric vector of length N+1.\n//' @export\n// [[Rcpp::export]]\nNumericVector hermite_function_sum(int N, NumericVector x, \n NumericVector normalization) {\n int x_size = x.size();\n NumericMatrix hermite(N + 1, x_size);\n NumericVector out(N + 1);\n NumericVector expFac(x_size);\n int i = 0;\n int j = 0;\n for(i = 0; i <= x_size-4; i += 4) {\n hermite(0,i) = 1;\n hermite(0,i+1) = 1;\n hermite(0,i+2) = 1;\n hermite(0,i+3) = 1;\n expFac(i) = exp(-1 * x[i] * x[i] / 2);\n expFac(i+1) = exp(-1 * x[i+1] * x[i+1] / 2);\n expFac(i+2) = exp(-1 * x[i+2] * x[i+2] / 2);\n expFac(i+3) = exp(-1 * x[i+3] * x[i+3] / 2);\n out(0) += (hermite(0,i) * expFac(i) +\n hermite(0,i+1) * expFac(i+1) +\n hermite(0,i+2) * expFac(i+2) +\n hermite(0,i+3) * expFac(i+3)) * normalization[0]; \n }\n for(; i < x_size; ++i) {\n hermite(0,i) = 1;\n expFac(i) = exp(-1 * x[i] * x[i] / 2);\n out(0) += hermite(0,i) * normalization[0] * expFac(i);\n }\n if (N==0){\n return out;\n }\n for(i = 0; i <= x_size - 4; i += 4) {\n hermite(1,i) = 2 * x[i];\n hermite(1,i+1) = 2 * x[i+1];\n hermite(1,i+2) = 2 * x[i+2];\n hermite(1,i+3) = 2 * x[i+3];\n out(1) += (hermite(1,i) * expFac(i) +\n hermite(1,i+1) * expFac(i+1) +\n hermite(1,i+2) * expFac(i+2) +\n hermite(1,i+3) * expFac(i+3)) * normalization[1];\n }\n for(; i < x_size; ++i) {\n hermite(1,i) = 2 * x[i];\n out(1) += hermite(1,i) * normalization[1] * expFac(i);\n }\n if (N==1){\n return out;\n }\n for(j = 0; j <= x_size - 4; j += 4) {\n for(int k = 2; k <= N; ++k) {\n hermite(k,j) = 2 * x[j] * hermite(k - 1,j) - 2 *\n (((double)k) - 1) * hermite(k - 2,j); \n hermite(k,j+1) = 2 * x[j+1] * hermite(k - 1,j+1) - 2 *\n (((double)k) - 1) * hermite(k - 2,j+1);\n hermite(k,j+2) = 2 * x[j+2] * hermite(k - 1,j+2) - 2 *\n (((double)k) - 1) * hermite(k - 2,j+2);\n hermite(k,j+3) = 2 * x[j+3] * hermite(k - 1,j+3) - 2 *\n (((double)k) - 1) * hermite(k - 2,j+3);\n out(k) += (hermite(k,j) * expFac(j) +\n hermite(k,j+1) * expFac(j+1) +\n hermite(k,j+2) * expFac(j+2) +\n hermite(k,j+3) * expFac(j+3)) * normalization[k]; \n \n }\n }\n for(; j < x_size; ++j) {\n for(int k = 2; k <= N; ++k) {\n hermite(k,j) = 2 * x[j] * hermite(k - 1,j) - 2 *\n (((double)k) - 1) * hermite(k - 2,j);\n out(k) += hermite(k,j) * normalization[k] * expFac(j);\n }\n }\n return out;\n}\n\n//' Outputs lower integral of the orthonormal Hermite functions\n//' \n//' The method calculates \\eqn{\\int_{-\\infty}^{x} h_k(t) dt} \n//' for \\eqn{k=0,\\dots,N} and the vector of values x.\n//' \n//' @author Michael Stephanou \n//'\n//' @param N An integer number.\n//' @param x A numeric vector.\n//' @param hermite_function_mat A numeric matrix of Hermite function values \n//' generated by the function hermite_function.\n//' @return A numeric matrix with N+1 rows and length(x) columns.\n//' @export\n// [[Rcpp::export]]\nNumericMatrix hermite_integral_val(int N, NumericVector x, \n NumericMatrix hermite_function_mat) {\n int x_size = x.size();\n NumericMatrix out(N + 1, x_size);\n for(int i = 0; i < x_size; ++i) {\n out(0,i) = pow(M_PI,0.25)/sqrt((double) 2) *\n boost::math::erfc((double) -1 * (1 / sqrt((double)2)) * x[i]); \n }\n if (N == 0){\n return out;\n }\n for(int i = 0; i < x_size; ++i) {\n out(1,i) = -1 * sqrt((double) 2)/pow(M_PI,0.25) *exp(-1 * x[i] * x[i] / 2); \n }\n if (N == 1){\n return out;\n }\n for(int i = 2; i <= N; ++i) {\n for(int j = 0; j < x_size; ++j) {\n out(i,j) = -1 * sqrt(2/((double)i)) * hermite_function_mat(i - 1,j) + \n sqrt((((double)i) - 1)/((double)i)) * out(i - 2,j);\n }\n }\n return out;\n}\n\n//' Outputs upper integral of the orthonormal Hermite functions\n//' \n//' The method calculates \\eqn{\\int_{x}^{\\infty} h_k(t) dt} \n//' for \\eqn{k=0,\\dots,N} and the vector of values x.\n//' \n//' @author Michael Stephanou \n//'\n//' @param N An integer number.\n//' @param x A numeric vector.\n//' @param hermite_function_mat A numeric matrix of Hermite function values \n//' generated by the function hermite_function.\n//' @return A numeric matrix with N+1 rows and length(x) columns.\n//' @export\n// [[Rcpp::export]]\nNumericMatrix hermite_integral_val_upper(int N,\n NumericVector x, NumericMatrix hermite_function_mat) {\n int x_size = x.size();\n NumericMatrix out(N + 1, x_size);\n for(int i = 0; i < x_size; ++i) {\n out(0,i) = pow(M_PI,0.25)/sqrt((double) 2) *\n boost::math::erfc((double) (1 / sqrt((double) 2)) * x[i]); \n }\n if (N == 0){\n return out;\n }\n for(int i = 0; i < x_size; ++i) {\n out(1,i) = sqrt((double) 2)/pow(M_PI,0.25) *exp(-1 * x[i] * x[i] / 2); \n }\n if (N == 1){\n return out;\n }\n for(int i = 2; i <= N; ++i) {\n for(int j = 0; j < x_size; ++j) {\n out(i,j) = sqrt(((double)2) / ((double)i)) * hermite_function_mat(i-1,j)+ \n sqrt((((double)i)-1)/((double)i)) * out(i-2,j);\n }\n }\n return out;\n}\n\n//' Outputs integral of the orthonormal Hermite functions on the full domain\n//' \n//' The method calculates \\eqn{\\int_{-\\infty}^{\\infty} h_k(t) dt} \n//' for \\eqn{k=0,\\dots,N}.\n//' \n//' @author Michael Stephanou \n//'\n//' @param N An integer number.\n//' @return A numeric matrix with N+1 rows and 1 columns.\n//' @export\n// [[Rcpp::export]]\nNumericMatrix hermite_int_full_domain(int N) {\n NumericMatrix out(N + 1, 1);\n out(0,0) = pow(M_PI,0.25)*sqrt((double) 2); \n if (N == 0){\n return out;\n }\n out(1,0) = 0; \n if (N == 1){\n return out;\n }\n for(int i = 2; i <= N; ++i) {\n out(i,0) = sqrt((((double)i)-1)/((double)i)) * out(i-2,0);\n }\n return out;\n}\n\n//' Standardizes the observation x and updates the online moment inputs\n//' \n//' @author Michael Stephanou \n//' \n//' @param x A numeric value.\n//' @param n_obs A numeric value. The number of observations.\n//' @param current_mean A numeric value. \n//' @param current_var A numeric value. \n//' @return A numeric vector. The first element is the updated mean. The\n//' second element is the updated variance times n_obs. The third element is the\n//' updated, standardized value of x.\n//' @export\n// [[Rcpp::export]]\nNumericVector standardizeInputs(double x, double n_obs, double current_mean,\n double current_var) {\n NumericVector outputVec(3);\n double prev_running_mean = current_mean;\n outputVec[0] = (current_mean * (n_obs - 1) + x) / n_obs;\n if (n_obs < 2){\n return outputVec;\n }\n outputVec[1] = current_var + (x - prev_running_mean) * (x - outputVec[0]);\n double running_std = sqrt(outputVec[1] / (n_obs - 1));\n outputVec[2] = (x - outputVec[0]) / running_std;\n return outputVec;\n}\n\n//' Standardizes the observation x and updates the online moment inputs\n//' \n//' The online moments are updated via exponential weighting.\n//' \n//' @author Michael Stephanou \n//'\n//' @param x A numeric value.\n//' @param n_obs A numeric value. The number of observations.\n//' @param lambda A numeric value.\n//' @param current_mean A numeric value.\n//' @param current_var A numeric value. \n//' @return A numeric vector. The first element is the updated mean. The\n//' second element is the updated variance times n_obs. The third element is the\n//' updated, standardized value of x.\n//' @export\n// [[Rcpp::export]]\nNumericVector standardizeInputsEW(double x, double n_obs,double lambda,\n double current_mean, double current_var) {\n NumericVector outputVec(3);\n if (n_obs < 2){\n current_mean = x;\n current_var = 1;\n outputVec[0] = current_mean;\n outputVec[1] = current_var;\n return outputVec;\n }\n outputVec[0] = (1 - lambda) * current_mean + lambda * x;\n current_var = (1 - lambda) * current_var + lambda * pow((x - outputVec[0]),2);\n outputVec[1] = current_var;\n double running_std = sqrt(current_var);\n outputVec[2] = (x - outputVec[0]) / running_std;\n return outputVec;\n}\n", "meta": {"hexsha": "0974215222d8e59d239cea0dfe7180d3902cc0fd", "size": 11837, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/hermite_utils.cpp", "max_stars_repo_name": "MikeJaredS/hermiter", "max_stars_repo_head_hexsha": "9e574098d28143fcfe03b04a3543cea40d7d381b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-08-30T11:47:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T13:04:41.000Z", "max_issues_repo_path": "src/hermite_utils.cpp", "max_issues_repo_name": "MikeJaredS/hermiter", "max_issues_repo_head_hexsha": "9e574098d28143fcfe03b04a3543cea40d7d381b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-12-14T10:57:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-19T05:50:26.000Z", "max_forks_repo_path": "src/hermite_utils.cpp", "max_forks_repo_name": "MikeJaredS/hermiter", "max_forks_repo_head_hexsha": "9e574098d28143fcfe03b04a3543cea40d7d381b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-08T05:07:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-08T05:07:56.000Z", "avg_line_length": 31.9918918919, "max_line_length": 80, "alphanum_fraction": 0.5862127228, "num_tokens": 3953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895028, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7740796393613697}} {"text": "#ifndef FUNCTIONS_H\n#define FUNCTIONS_H\n\n#include \"types.hpp\"\n#include \n#include \n#include \n\nnamespace Optima {\n\nclass TestFunctions {\n\npublic:\n\n /**\n * N-Dimensional generalization of the Ackley function\n *\n * This function has a minimum when all parameter values are zero.\n *\n * The hyper parameters for this function are hard coded to the following:\n * a = 20\n * b = 0.2\n * c = 2 * pi\n *\n * @param params :: n dimensional array of x values\n * @return value of the function evaluated with the given parameters\n */\n static double ackley(const Parameters ¶ms) {\n const double a = 20;\n const double b = 0.2;\n const double c = 2 * M_PI;\n\n double powerSum = std::accumulate(params.begin(), params.end(), 0, \n [](const double sum, const std::pair& item) {\n return sum + std::pow(item.second, 2.0);\n });\n\n double cosSum = std::accumulate(params.begin(), params.end(), 0, \n [&c](const double sum, const std::pair& item) {\n return sum + std::cos(c*item.second);\n });\n\n cosSum *= 1. / params.size();\n powerSum *= 1. / params.size();\n powerSum = std::sqrt(powerSum);\n\n return -a * std::exp( -b * powerSum ) - std::exp(cosSum) + a + std::exp(1);\n }\n\n /**\n * N-Dimensional generalization of the Rosenbrock function\n *\n * The minimum of this function will be at zero\n *\n * @param vec :: n dimensional array of x values\n * @return value of the function evaluated at the point defined by vec\n */\n static double rosen(const Parameters ¶ms) {\n using namespace std;\n double y = 0;\n for (size_t i = 0; i < params.size() - 1; ++i) {\n const double x1 = params.at(\"x\" + std::to_string(i));\n const double x2 = params.at(\"x\" + std::to_string(i + 1));\n y += 100 * pow(x2 - pow(x1, 2.0), 2.0) + pow(1 - x1, 2.0);\n }\n\n return y;\n }\n\n /**\n * N-Dimensional parabolic function centered on the origin.\n *\n * The function has the form x1**2 + x2**2 + ... + xn**2 = y\n *\n * The minimum of this function will be at zero\n *\n * @param vec :: n dimensional arry of x values\n * @return value of the function evaludated at the point defined by vec\n */\n static double parabola(const Parameters ¶ms) {\n using namespace std;\n double y = 0;\n for (const auto ¶m : params)\n y += std::pow(param.second, 2.0);\n\n return y;\n }\n\n};\n}\n#endif // FUNCTIONS_H\n", "meta": {"hexsha": "7d962a9edd3eb916d02be7d979b17a474bba08b1", "size": 2700, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/functions.hpp", "max_stars_repo_name": "samueljackson92/metaopt", "max_stars_repo_head_hexsha": "8d030476a20b8a2661f44f3b2355880689874b96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/functions.hpp", "max_issues_repo_name": "samueljackson92/metaopt", "max_issues_repo_head_hexsha": "8d030476a20b8a2661f44f3b2355880689874b96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-04-30T08:27:07.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T08:36:20.000Z", "max_forks_repo_path": "src/functions.hpp", "max_forks_repo_name": "samueljackson92/metaopt", "max_forks_repo_head_hexsha": "8d030476a20b8a2661f44f3b2355880689874b96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.347826087, "max_line_length": 84, "alphanum_fraction": 0.56, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7740378524540719}} {"text": "// ALGOLAB BGL Tutorial 3\n// Code snippets demonstrating \n// - MinCostMaxFlow with negative edge costs using cycle_canceling\n// - MinCostMaxFlow with negative edge costs using successive_shortest_path_nonnegative_weights\n\n// Compile and run with one of the following:\n// g++ -std=c++11 -O2 bgl_mincostmaxflow.cpp -o bgl_mincostmaxflow; ./bgl_mincostmaxflow\n// g++ -std=c++11 -O2 -I path/to/boost_1_58_0 bgl_mincostmaxflow.cpp -o bgl_mincostmaxflow; ./bgl_mincostmaxflow\n\n// Includes\n// ========\n// STL includes\n#include \n#include \n// BGL includes\n#include \n#include \n#include \n#include \n#include \n// Namespaces\nusing namespace boost;\nusing namespace std;\n\n// BGL Graph definitions\n// ===================== \n// Graph Type with nested interior edge properties for Cost Flow Algorithms\ntypedef adjacency_list_traits Traits;\ntypedef adjacency_list > > > > Graph;\n// Interior Property Maps\ntypedef property_map::type EdgeCapacityMap;\ntypedef property_map::type EdgeWeightMap;\ntypedef property_map::type ResidualCapacityMap;\ntypedef property_map::type ReverseEdgeMap;\ntypedef graph_traits::vertex_descriptor Vertex;\ntypedef graph_traits::edge_descriptor Edge;\ntypedef graph_traits::out_edge_iterator OutEdgeIt; // Iterator\n\n// Custom Edge Adder Class, that holds the references\n// to the graph, capacity map, weight map and reverse edge map\n// ===============================================================\nclass EdgeAdder {\n Graph &G;\n EdgeCapacityMap &capacitymap;\n EdgeWeightMap &weightmap;\n ReverseEdgeMap &revedgemap;\n\npublic:\n EdgeAdder(Graph & G, EdgeCapacityMap &capacitymap, EdgeWeightMap &weightmap, ReverseEdgeMap &revedgemap) \n : G(G), capacitymap(capacitymap), weightmap(weightmap), revedgemap(revedgemap) {}\n\n void addEdge(int u, int v, long c, long w) {\n Edge e, reverseE;\n tie(e, tuples::ignore) = add_edge(u, v, G);\n tie(reverseE, tuples::ignore) = add_edge(v, u, G);\n capacitymap[e] = c;\n weightmap[e] = w;\n capacitymap[reverseE] = 0;\n weightmap[reverseE] = -w;\n revedgemap[e] = reverseE; \n revedgemap[reverseE] = e; \n }\n};\n\nint main() {\n const int N=7;\n const int v_source = 0;\n const int v_farm1 = 1;\n const int v_farm2 = 2;\n const int v_farm3 = 3;\n const int v_shop1 = 4;\n const int v_shop2 = 5;\n const int v_target = 6;\n\n // Create Graph and Maps\n Graph G(N);\n EdgeCapacityMap capacitymap = get(edge_capacity, G);\n EdgeWeightMap weightmap = get(edge_weight, G);\n ReverseEdgeMap revedgemap = get(edge_reverse, G);\n ResidualCapacityMap rescapacitymap = get(edge_residual_capacity, G);\n EdgeAdder eaG(G, capacitymap, weightmap, revedgemap);\n \n // Add the edges\n eaG.addEdge(v_source,v_farm1,3,0);\n eaG.addEdge(v_source,v_farm2,1,0);\n eaG.addEdge(v_source,v_farm3,2,0);\n\n eaG.addEdge(v_farm1,v_shop1,1,1);\n eaG.addEdge(v_farm1,v_shop2,1,5);\n eaG.addEdge(v_farm2,v_shop1,1,2);\n eaG.addEdge(v_farm2,v_shop2,1,2);\n eaG.addEdge(v_farm3,v_shop1,1,3);\n eaG.addEdge(v_farm3,v_shop2,2,2);\n\n eaG.addEdge(v_shop1,v_target,3,0);\n eaG.addEdge(v_shop2,v_target,3,0);\n\n // Run the algorithm\n\n // Option 1: Min Cost Max Flow with cycle_canceling\n int flow1 = push_relabel_max_flow(G, v_source, v_target);\n cycle_canceling(G);\n int cost1 = find_flow_cost(G);\n cout << \"-----------------------\" << endl;\n cout << \"Minimum Cost Maximum Flow with cycle_canceling()\" << endl;\n cout << \"flow \" << flow1 << endl; // 5\n cout << \"cost \" << cost1 << endl; // 12\n\n // Option 2: Min Cost Max Flow with successive_shortest_path_nonnegative_weights\n successive_shortest_path_nonnegative_weights(G, v_source, v_target);\n int cost2 = find_flow_cost(G);\n int flow2 = 0;\n // Iterate over all edges leaving the source to sum up the flow values.\n OutEdgeIt e, eend;\n for(tie(e, eend) = out_edges(vertex(v_source,G), G); e != eend; ++e) {\n flow2 += capacitymap[*e] - rescapacitymap[*e];\n }\n cout << \"-----------------------\" << endl;\n cout << \"Minimum Cost Maximum Flow with successive_shortest_path_nonnegative_weights()\" << endl;\n cout << \"flow \" << flow2 << endl; // 5\n cout << \"cost \" << cost2 << endl; // 12\n cout << \"-----------------------\" << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "deddc6f7cc2552756012709b8c3a0dfd0c85e0c5", "size": 4932, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week9/examples/tut9_bgl_mincostmaxflow.cpp", "max_stars_repo_name": "KarlKode/algo-lab", "max_stars_repo_head_hexsha": "69bf7e65bda465e09b72f4adaddee3f65e7a7567", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "week9/examples/tut9_bgl_mincostmaxflow.cpp", "max_issues_repo_name": "KarlKode/algo-lab", "max_issues_repo_head_hexsha": "69bf7e65bda465e09b72f4adaddee3f65e7a7567", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week9/examples/tut9_bgl_mincostmaxflow.cpp", "max_forks_repo_name": "KarlKode/algo-lab", "max_forks_repo_head_hexsha": "69bf7e65bda465e09b72f4adaddee3f65e7a7567", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9384615385, "max_line_length": 112, "alphanum_fraction": 0.6697080292, "num_tokens": 1362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929799, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.773953545539365}} {"text": "#include \n\n#include \n\nEigen::MatrixXd Jacobian(const Eigen::MatrixXd &A, Eigen::VectorXd &z) {\n\tint n = z.size() - 1;\t\n\tint lambda = z(n);\n\n\tEigen::MatrixXd J(n + 1, n + 1);\n\tJ.topLeftCorner(n , n) = (A - z(n) * Eigen::MatrixXd::Identity(n, n));\n\tJ.row(n) = -z.transpose();\n\tJ.col(n) = -z;\n\n\t// overwrite value back to 0\n\tJ(n, n) = 0;\n\n\treturn J;\n}\n\nvoid eigNewton(const Eigen::MatrixXd &A, double tol, int maxItr, Eigen::VectorXd &z) {\n\n\tint n = z.size() - 1;\n\tEigen::VectorXd F(n + 1);\n\n\tfor(int i = 0; i < maxItr; i++) {\n\t\tEigen::VectorXd x = z.head(n);\n\t\tF.head(n) = A * x - z(n) * x;\n\t\tF(n) = 1 - 0.5 * x.squaredNorm();\n\t\t\n\t\tif(F.squaredNorm() < tol) {\n\t\t\treturn;\t\t\n\t\t}\n\n\t\tz += Jacobian(A, z).fullPivLu().solve(-F);\n\t}\n}\n\nint main() {\n\tint n = 2;\n\tint m = n + 1;\n\n\tEigen::VectorXd x = Eigen::VectorXd::Ones(n);\n\tx << 1.0, 0.0;\n\tdouble lambda = 0.0;\n\n\tEigen::VectorXd z(m);\n\tz.head(n) = x;\n\tz(n) = lambda;\n\n\tEigen::MatrixXd A = Eigen::MatrixXd::Ones(n, n);\n\tA << 2, 1, 1, 2;\n\n\teigNewton(A, .0001, 10, z);\n\n\tstd::cout << \"eigenvector:\" << std::endl;\n\tstd::cout << z.head(n) << std::endl;\n\tstd::cout << \"eigenvalue: \" << z(n) << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "cf2b4485217515abc334cada76d8bb3c6773dd31", "size": 1179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mockExam/ex_eigNewton/eigNewton.cpp", "max_stars_repo_name": "azurite/numCSE18-code", "max_stars_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-13T19:08:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-13T19:08:32.000Z", "max_issues_repo_path": "mockExam/ex_eigNewton/eigNewton.cpp", "max_issues_repo_name": "azurite/numCSE18-code", "max_issues_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mockExam/ex_eigNewton/eigNewton.cpp", "max_forks_repo_name": "azurite/numCSE18-code", "max_forks_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_forks_repo_licenses": ["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.3278688525, "max_line_length": 86, "alphanum_fraction": 0.5555555556, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966747198242, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7739132847082427}} {"text": "#ifndef matrix_hpp\n#define matrix_hpp\n\n#include \n#include \n#include \n\nnamespace threedimutil\n{\n inline Eigen::Matrix4d make_perspective(double fov,\n double aspect,\n double near,\n double far)\n {\n const double val = std::tan(0.5 * fov);\n\n Eigen::Matrix4d mat = Eigen::Matrix4d::Zero();\n mat(0, 0) = 1.0 / (aspect * val);\n mat(1, 1) = 1.0 / (val);\n mat(2, 2) = far / (near - far);\n mat(3, 2) = - 1.0;\n mat(2, 3) = - 2.0 * (far * near) / (far - near);\n\n return mat;\n }\n\n inline Eigen::Matrix4d make_perspective(double fov,\n unsigned frame_width,\n unsigned frame_height,\n double near,\n double far)\n {\n const double aspect = static_cast(frame_width) / static_cast(frame_height);\n\n return make_perspective(fov, aspect, near, far);\n }\n\n inline Eigen::Matrix4d make_look_at(const Eigen::Vector3d& camera_position,\n const Eigen::Vector3d& target_position,\n const Eigen::Vector3d& up_direction)\n {\n Eigen::Matrix4d mat = Eigen::Matrix4d::Identity();\n\n const Eigen::Vector3d forward = (target_position - camera_position).normalized();\n const Eigen::Vector3d side = forward.cross(up_direction).normalized();\n const Eigen::Vector3d up = side.cross(forward);\n\n mat.block<1, 3>(0, 0) = side.transpose();\n mat.block<1, 3>(1, 0) = up.transpose();\n mat.block<1, 3>(2, 0) = - forward.transpose();\n mat(0, 3) = - side.dot(camera_position);\n mat(1, 3) = - up.dot(camera_position);\n mat(2, 3) = forward.dot(camera_position);\n\n return mat;\n }\n \n inline Eigen::Matrix4d make_look_at(const Camera& camera)\n {\n return make_look_at(camera.position(), camera.target(), camera.up());\n }\n \n inline Eigen::Matrix4d make_ortho(double left,\n double right,\n double bottom,\n double top,\n double near,\n double far)\n {\n const double dx = right - left;\n const double dy = top - bottom;\n const double dz = far - near;\n const double tx = - (right + left) / dx;\n const double ty = - (top + bottom) / dy;\n const double tz = - (far + near) / dz;\n return (Eigen::Matrix4d() <<\n 2.0 / dx, 0.0, 0.0, tx,\n 0.0, 2.0 / dy, 0.0, ty,\n 0.0, 0.0, - 2.0 / dz, tz,\n 0.0, 0.0, 0.0, 1.0\n ).finished();\n }\n\n inline Eigen::Matrix4d make_ortho_2d(double left,\n double right,\n double bottom,\n double top)\n {\n const double dx = right - left;\n const double dy = top - bottom;\n const double tx = - (right + left) / dx;\n const double ty = - (top + bottom) / dy;\n return (Eigen::Matrix4d() <<\n 2.0 / dx, 0.0, 0.0, tx,\n 0.0, 2.0 / dy, 0.0, ty,\n 0.0, 0.0, - 1.0, 0.0,\n 0.0, 0.0, 0.0, 1.0\n ).finished();\n }\n}\n\n#endif /* matrix_hpp */\n", "meta": {"hexsha": "ab12d2e0dbbb2c6c29276782d14b217b7bbc81c6", "size": 3773, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/three-dim-util/matrix.hpp", "max_stars_repo_name": "yuki-koyama/3d-util", "max_stars_repo_head_hexsha": "e3eca11f300d9af6cc5d3eb5636c62f95276de59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-10-13T15:16:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T06:07:55.000Z", "max_issues_repo_path": "include/three-dim-util/matrix.hpp", "max_issues_repo_name": "yuki-koyama/3d-util", "max_issues_repo_head_hexsha": "e3eca11f300d9af6cc5d3eb5636c62f95276de59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-05-14T00:34:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-20T13:50:42.000Z", "max_forks_repo_path": "include/three-dim-util/matrix.hpp", "max_forks_repo_name": "yuki-koyama/3d-util", "max_forks_repo_head_hexsha": "e3eca11f300d9af6cc5d3eb5636c62f95276de59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-03-18T07:36:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T19:42:33.000Z", "avg_line_length": 36.6310679612, "max_line_length": 99, "alphanum_fraction": 0.4407633183, "num_tokens": 915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474220263198, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7737216029538835}} {"text": "/*\n fft.cpp\n\n nabla^2 u = exp(-x^2-y^2) on (0,1)^2 w/ u=0 on BC\n\ng++ -I/usr/local/include/eigen3\n\n*/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nvoid sineTransform2D(Eigen::MatrixXd & Mk, const Eigen::MatrixXd & Mx) {\n // Mk_{nm} = sum_{ij=1}^{N-1} Mx_{ij} sin(in pi/N) sin (jm pi/N)\n int N = Mx.rows();\n int M = Mx.cols();\n Eigen::FFT fft;\n Eigen::MatrixXd Mrow(N,M);\n std::vector f(2*N,0.0);\n std::vector > fkk(2*N,0.0);\n // sine transform rows\n for (int j=0;j> N ;\n double del = 1.0/(N+1);\n\n Eigen::MatrixXd rho(N+1,N+1);\n Eigen::MatrixXd rhoHat(N+1,N+1);\n Eigen::MatrixXd uHat(N+1,N+1);\n Eigen::MatrixXd u(N+1,N+1);\n\n for (int i=1;i\n#include \n#include \n// Eigen includes\n#include \n\nnamespace WaveABC2D {\n\n/** @brief The evolution is performed by successively solving a linear sytem\n *\n * A * x(k) = b(k-1)\n *\n * at each time step. The matrix A is independent of time and completely\n * determined by the equation's parameter epsilon and the fixed uniform step\n * size of the method. Here, x will be a (M + 1) x 2 matrix storing the discrete\n * solution in its first column and the discrete time derivative in the second\n * column. The discrete time derivative is needed, because it is introduced as\n * an unknown in the implicit method to reduce the order of the ODE.\n *\n * @param epsilon Equation parameter in [0,1].\n * @param M Number of timesteps.*/\n/* SAM_LISTING_BEGIN_1 */\nEigen::VectorXd scalarImplicitTimestepping(double epsilon, unsigned int M) {\n /* PROBLEM SETUP */\n double step_size = 1.0 / M; // time step \"tau\"\n // Rows contain sequence of solutions states\n Eigen::MatrixXd x(M + 1, 2);\n // INITIAL DATA\n x(0, 0) = 1.0;\n x(0, 1) = 1.0;\n\n Eigen::MatrixXd A(2, 2);\n Eigen::VectorXd b(2);\n // clang-format off\n A << epsilon + 0.5*step_size*(1-epsilon), 0.5*step_size,\n -0.5*step_size, 1.0;\n // clang-format on\n // TIMESTEPPING\n for (int k = 1; k < M + 1; k++) {\n // Update right hand side\n b(0) = (epsilon - 0.5 * step_size * (1 - epsilon)) * x(k - 1, 0) -\n 0.5 * step_size * x(k - 1, 1);\n b(1) = x(k - 1, 1) + 0.5 * step_size * x(k - 1, 0);\n // Solve the linear system\n x.row(k) = A.fullPivLu().solve(b);\n }\n return x.col(1);\n} // scalarImplicitTimestepping\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\nvoid testConvergenceScalarImplicitTimestepping() {\n std::cout << \"Testing convergence of the implicit method.\" << std::endl;\n int nIter = 13; // total number of iterations\n unsigned int M; // number of equidistant steps\n double step_size; // time step \"tau\"\n double epsilon = 0.2;\n\n // Error between the approx solutions as given by the implicit method\n // and the exact solution vector computed from the anlytic formula vector\n // computed from the anlytic formula\n std::cout << \"Computing approximate solutions...\" << std::endl;\n double diff; // temporary variable used to compute error at various nodes\n double max_norm_errors[nIter]; // errors vector for all approx. sols\n Eigen::VectorXd approx_sol_vec;\n Eigen::VectorXd exact_sol_vec;\n unsigned int M_stored[13] = {10, 20, 30, 40, 50, 60, 80,\n 100, 160, 200, 320, 500, 640};\n for (int k = 0; k < nIter; k++) {\n // M = 10 * std::pow(2, k);\n M = M_stored[k];\n exact_sol_vec.resize(M + 1);\n step_size = 1.0 / M;\n // Creating exact solution vector for epsilon = 1/5. This vector is created\n // by evaluating the exact solution using the analytic formula\n // x(t) = exp(-2*t)*cos(t)\n // at the equidistant nodes of the time steps.\n for (int i = 0; i < M + 1; i++) {\n exact_sol_vec(i) =\n std::exp(-2 * i * step_size) *\n (3 * std::sin(i * step_size) + std::cos(i * step_size));\n }\n // Computing approximate solution\n approx_sol_vec = scalarImplicitTimestepping(epsilon, M);\n // Computing the error in the maximum norm\n for (int i = 0; i < M + 1; i++) {\n max_norm_errors[k] = 0;\n diff = std::abs(approx_sol_vec(i) - exact_sol_vec(i));\n max_norm_errors[k] =\n (diff > max_norm_errors[k]) ? diff : max_norm_errors[k];\n }\n }\n // Computing rates of convergence\n /*std::cout << \"Computing convergence rates...\" << std::endl;\n double rates[nIter - 1];\n double avg_rate = 0.0;\n for (int k = 0; k < nIter - 1; k++) {\n rates[k] = log2(max_norm_errors[k] / max_norm_errors[k + 1]);\n avg_rate += rates[k];\n }\n avg_rate = avg_rate / (nIter - 1);\n */\n /* SAM_LISTING_END_2 */\n\n // Printing results\n std::cout << \"\\n\" << std::endl;\n std::cout << \"*********************************************************\"\n << std::endl;\n std::cout << \" Convergence of the Implicit Method \"\n << \"\\n (epsilon = \" << epsilon << \")\" << std::endl;\n std::cout << \"*********************************************************\"\n << std::endl;\n std::cout << \"--------------------- RESULTS ---------------------------\"\n << std::endl;\n std::cout << \"Iteration\"\n << \"\\t| Nsteps\"\n << \"\\t| error\" << std::endl;\n // << \"\\t\\t| rates\" << std::endl;\n std::cout << \"---------------------------------------------------------\"\n << std::endl;\n for (int k = 0; k < nIter; k++) {\n std::cout << k << \"\\t\"\n << \"\\t|\" << M_stored[k] /*10 * std::pow(2, k)*/ << \"\\t\\t|\"\n << max_norm_errors[k];\n /* if (k > 0) {\n std::cout << \"\\t|\" << rates[k - 1];\n }\n */\n std::cout << \"\\n\";\n }\n std::cout << \"---------------------------------------------------------\"\n << std::endl;\n /* std::cout << \"Average rate of convergence: \" << avg_rate << \"\\n\" <<\n * std::endl;\n */\n\n} // testConvergenceScalarImplicitTimestepping\n/* SAM_LISTING_END_2 */\n\n/* Implementing member functions of class progress_bar */\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 os << '\\r' << message;\n os.write(full_bar.data() + offset, width);\n os << \" [\" << std::setw(3) << static_cast(100 * fraction) << \"%] \"\n << std::flush;\n}\n\n} // namespace WaveABC2D\n", "meta": {"hexsha": "61312155e558005d83fbcd359e54c32058a5950c", "size": 5938, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/WaveABC2D/mastersolution/waveabc2d.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/WaveABC2D/mastersolution/waveabc2d.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/WaveABC2D/mastersolution/waveabc2d.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": 35.5568862275, "max_line_length": 80, "alphanum_fraction": 0.5540586056, "num_tokens": 1705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7736362604691358}} {"text": "#pragma once\n\n#include \n\nnamespace math\n{\n\n// Returns true if the matrices are element-wise equal within tolerance.\n// Throws an exception if the two matrices are of different sizes.\nbool is_equal(const Eigen::MatrixXd &mat1, const Eigen::MatrixXd &mat2, const double tol=1e-12);\n\n// Returns true if a matrix is equal to its transpose. Returns false otherwise. \n// Throws an exception if the matrix is not square.\nbool is_symmetric(const Eigen::MatrixXd &mat, const double tol=1e-12);\n\n// Computes the Gradient of func() using finite differencing around pt. The gradient has the same dimensions as the\n// input for func(), which should be the same as the dimension of pt.\nEigen::VectorXd gradient(\n const std::function &func, \n const Eigen::VectorXd &pt, \n const double delta = 1e-2);\n\n// Computes the Jacobian of func() using finite differencing around pt. Jacobian has dimension [output_dim x input_dim]\n// where output_dim is the dimension of the output of func() and input_dim is the input dimension of\n// func(), which should be same as the dimension of pt.\nEigen::MatrixXd jacobian(\n const std::function &func, \n const Eigen::VectorXd &pt, \n const double delta = 1e-2);\n\n// Computes the Hessian of func() using finite differencing around pt. The Hessian has dimension [input_dim x input_dim]\n// where input_dim is the dimension of the input for func(), which should be the same as the\n// dimension of pt.\nEigen::MatrixXd hessian(\n const std::function &func, \n const Eigen::VectorXd &pt, \n const double delta = 1e-2);\n\n// Projects a symmetric matrix onto the PSD (positive semi-definite) cone by bumping up any \n// eigenvalues <= 0 to min_eigval. If min_eigval is 0 this projects onto the boundary of the PSD cone.\n// For numerical stability, a value higher than 0 is recommended.\nEigen::MatrixXd project_to_psd(const Eigen::MatrixXd &symmetric_mat, const double min_eigval = 0);\n\n// Throws exception if the matrix mat is not positive-semi definite with all eigenvalues\n// greater than the specified min_eigval.\nvoid check_psd(const Eigen::MatrixXd &square_mat, const double min_eigval = 0);\n\n} // namespace math\n\n", "meta": {"hexsha": "2ad038d66ce50956c0c7c6d26a022cbee1e30122", "size": 2301, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/utils/math_utils.hh", "max_stars_repo_name": "LAIRLAB/qr_trees", "max_stars_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T08:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T08:42:33.000Z", "max_issues_repo_path": "src/utils/math_utils.hh", "max_issues_repo_name": "LAIRLAB/qr_trees", "max_issues_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/math_utils.hh", "max_forks_repo_name": "LAIRLAB/qr_trees", "max_forks_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-07-10T03:25:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T15:58:44.000Z", "avg_line_length": 46.02, "max_line_length": 120, "alphanum_fraction": 0.7366362451, "num_tokens": 543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.890294223211224, "lm_q2_score": 0.868826777936422, "lm_q1q2_score": 0.7735114613680174}} {"text": "#include \n#include \n\n#include // Eigen 核心部分\n#include // 稠密矩阵的代数运算(逆,特征值等)\n#include // Eigen/Geometry 模块提供了各种旋转和平移的表示\n\n#include \n#include \n\n#include \n\n\n\nstruct CURVE_FITTING_COST{\n\n CURVE_FITTING_COST(double t, double y): _t(t), _y(y) {}\n\n template\n bool operator() (const T *const x, T *residual) const {\n residual[0] = T(_y) - ceres::exp(x[0]*T(_t)*T(_t) + x[1]*T(_t) + x[2]);\n return true;\n }\n\n const double _t, _y;\n};\n\nint main(int argc, char **argv){\n\n double a_e = 2.0, b_e = -1.0, c_e = 5.0; // 待拟合参数 及估计初值\n double a = 1.0, b = 2.0, c = 1.0; // 待拟合参数 实际值\n cv::RNG rng; // OpenCV 随机数产生器\n double w_sigma = 1.0;\n double inv_sigma = 1.0 / w_sigma;\n\n // 生成数据\n int num_data = 100;\n std::vector t_data, y_data;\n \n for(int i = 0; i < num_data; i++){\n double t = i / 100.0;\n double y = exp(a*t*t + b*t + c) + rng.gaussian(w_sigma * w_sigma);\n t_data.push_back(t);\n y_data.push_back(y);\n }\n\n\n double x[3] = {a_e, b_e, c_e};\n \n // 构建最小二乘问题\n ceres::Problem problem;\n for(int i = 0; i < num_data; i++){\n problem.AddResidualBlock(\n new ceres::AutoDiffCostFunction(new \n CURVE_FITTING_COST(t_data[i], y_data[i])),\n nullptr,\n x\n );\n }\n\n // 配置求解器\n ceres::Solver::Options options;\n options.linear_solver_type = ceres::DENSE_NORMAL_CHOLESKY;\n options.minimizer_progress_to_stdout = true;\n\n ceres::Solver::Summary summary;\n std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now();\n ceres::Solve(options, &problem, &summary);\n \n std::chrono::steady_clock::time_point t2 = std::chrono::steady_clock::now();\n std::chrono::duration time_used = std::chrono::duration_cast > (t2 - t1);\n std::cout << \"time_cost = \" << time_used.count() << \"second\" << std::endl; \n\n std::cout << summary.BriefReport() << std::endl;\n std::cout << \"estimated_parameters = \" << x[0] << \" \" << x[1] << \" \" << x[2] << std::endl;\n return 0;\n}\n", "meta": {"hexsha": "2923bc8f13bc350aca2bbc160c0fb3390a5dd621", "size": 2241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "my_implementation_2/ch6/ceresCurveFitting/ceresCurveFitting.cpp", "max_stars_repo_name": "Mingrui-Yu/slambook2", "max_stars_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-09T14:18:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-09T14:18:15.000Z", "max_issues_repo_path": "my_implementation_2/ch6/ceresCurveFitting/ceresCurveFitting.cpp", "max_issues_repo_name": "Mingrui-Yu/slambook2", "max_issues_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "my_implementation_2/ch6/ceresCurveFitting/ceresCurveFitting.cpp", "max_forks_repo_name": "Mingrui-Yu/slambook2", "max_forks_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7307692308, "max_line_length": 115, "alphanum_fraction": 0.5921463632, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509314, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7733439135818774}} {"text": "#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n cout.precision(3);\n typedef Matrix DataMatrix;\n// let's generate some samples on the 3D plane of equation z = 2x+3y (with some noise)\nDataMatrix samples = DataMatrix::Random(12,2);\nVectorXf elevations = 2*samples.col(0) + 3*samples.col(1) + VectorXf::Random(12)*0.1;\n// and let's solve samples * [x y]^T = elevations in least square sense:\nMatrix xy\n = (samples.adjoint() * samples).llt().solve((samples.adjoint()*elevations));\ncout << xy << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "f693ddf66124d786afec07c284a83259e1ebe07f", "size": 607, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_LLT_solve.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_LLT_solve.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_LLT_solve.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": 28.9047619048, "max_line_length": 86, "alphanum_fraction": 0.7018121911, "num_tokens": 183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202038, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7729663738684992}} {"text": "/* C++ code for generating the Campbell-Robson CSF image.\n\nThis algorhtim generates one image in linear scale with the C(cols,rows)\nfunction, and another image in logarithmic scale with the Cl(cols,rowas)\nfunction.\n\n*/\n#include \"grapher.cpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include /* sqrt, sin, log, exp */\n\nusing namespace cv;\nusing namespace std;\nnamespace po = boost::program_options;\n\n// precalculated constant = sqrt(2)*pi\n#define sqrt2pi 4.442882938\n\n//computes a sinusoidal function with variable frecuency\n//given by: f = 1 / sqrt(2x)\ndouble s( double x, int cols);\n\n//computes a linear function with m = 127/(rows-1) and b = 0\ndouble a( double y, int rows);\n\n//creates the linear scale image given by:\n//C(x) = s(x)*a(y)+128\nMat C( int cols, int rows);\n\n//changes the linear varible x to a logarithmic scale\n// f(x) = k*exp(alfa*x)\n// f(0)\t= fmax = k\n// f(R-1) =\tR-1 \ndouble f( int x, int R);\n\n//Shows a row of a channel\nstd::vector channelRow(Mat *pChannel, int pRow);\n\n//creates the logarithmic scale image given by:\n//C(x) = s(f(x))*a(f(y))+128\nMat Cl( int cols, int rows);\n\nint main (int argc, const char* argv[])\n{\n\tint cols = 512;\n\tint rows = 512;\n int row;\n po::options_description description(\"ImageShow Usage\");\n description.add_options()\n (\"help,h\", \"Display this help message\")\n (\"rows,r\", po::value(), \"Rows size.\")\n (\"cols,c\", po::value(), \"Cols size.\")\n (\"showrow,x\", po::value(), \"Show row.\")\n (\"lineal,l\", \"Lineal scale.\");\n\n po::positional_options_description p;\n p.add(\"file\", -1);\n\n po::variables_map vm;\n po::store(po::command_line_parser(argc, argv).options(description).positional(p).run(), vm);\n po::notify(vm);\n\n if(vm.count(\"help\")){\n cout << description;\n return 0;\n }\n if(vm.count(\"rows\")){\n rows = vm[\"rows\"].as();\n }\n if(vm.count(\"cols\")){\n cols = vm[\"cols\"].as();\n }\n if(vm.count(\"lineal\")){\n namedWindow( \"lin\", WINDOW_AUTOSIZE );\n imshow( \"lin\", C(cols,rows) );\n waitKey(0);\n return 0;\n }\n if(vm.count(\"showrow\")){\n Mat tmp= Cl(cols,rows);\n row = vm[\"showrow\"].as();\n grapher graph((int)cols/2+10,5,(int)cols/2+10, 128);\n std::vector > posiciones(1, std::vector(cols));\n for(int i = 0; i< cols; i++){\n posiciones[0][i] = i;\n }\n std::vector > frecuencias;\n std::vector titulo;\n frecuencias.push_back(channelRow(&tmp,row));\n titulo.push_back(\"Fila\");\n std::cout << \"todo bien\" << std::endl;\n graph(&posiciones, &frecuencias, &titulo);\n waitKey(0);\n return 0;\n }\n\n//linear scale image\n //logarithmic scale image \n namedWindow( \"log\", WINDOW_AUTOSIZE );\n imshow( \"log\", Cl(cols,rows) );\n waitKey(0);\n return 0;\n}\n\n// x : input value\n// cols : maximum value / number of columns\ndouble s( double x, int cols){\n double correct = 0.125;\n\treturn sin (sqrt2pi * sqrt((cols-1)+correct-x));\n}\n\n// y : input value\n// rows : maximum value / number of rows\ndouble a( double y, int rows){\n\treturn 127.0/(rows-1)*y;\n}\n\n// cols : number of desired columns on the output image\n// rows : number of desired rows on the output image\nMat C( int cols, int rows){\n\tMat image(rows, cols, CV_8UC1, Scalar(0));\n \tfor(int x=0;x(y,x) = (uint8_t) (s(x,cols)*a(y,rows)+128);\n \t\t}\n \t}\n \treturn image;\n}\n\n// x : input value\n// R : maximum value\n// k : maximum frequency\ndouble f( int x, int R){\n\tdouble k = 10;\n\tdouble alfa = log(pow((double)(R-1)/k,(double)1/(R-1)));\n\treturn k*exp(alfa*x);\n}\n\n// cols : number of desired colums on the output image\n// rows : number of desired rows on the output image\nMat Cl( int cols, int rows){\n\tMat image(rows, cols, CV_8UC1, Scalar(0));\n \tfor(int x=0;x(y,x) = (uint8_t) (s(f(x,cols),cols)*a(f(y,rows),rows)+128);\n \t\t}\n \t}\n \treturn image;\n}\n\n/**\n*\n* @param pChannel mat with the image\n* @param pRow\n*/\nstd::vector channelRow(Mat *pChannel, int pRow){\n std::vector fondo (pChannel->cols, 0);\n for(unsigned i = 0; i< pChannel->cols; i++){\n fondo.at(i)=(int)pChannel->at(pRow, i);\n }\n return fondo;\n}\n", "meta": {"hexsha": "5216ae4b3dca3aea401704619a3a7342aa3f73f8", "size": 4487, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Procesamiento_y_analisis_de_imagenes_digitales/Campbell-Robson-letter/campbell-robson.cpp", "max_stars_repo_name": "malkam03/TEC-CR", "max_stars_repo_head_hexsha": "010bfb6df20167bf538bfe9e78fdb9c0467f4ce4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-19T21:55:18.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-19T21:55:18.000Z", "max_issues_repo_path": "Procesamiento_y_analisis_de_imagenes_digitales/Campbell-Robson-letter/campbell-robson.cpp", "max_issues_repo_name": "malkam03/TEC-CR", "max_issues_repo_head_hexsha": "010bfb6df20167bf538bfe9e78fdb9c0467f4ce4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Procesamiento_y_analisis_de_imagenes_digitales/Campbell-Robson-letter/campbell-robson.cpp", "max_forks_repo_name": "malkam03/TEC-CR", "max_forks_repo_head_hexsha": "010bfb6df20167bf538bfe9e78fdb9c0467f4ce4", "max_forks_repo_licenses": ["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.550295858, "max_line_length": 94, "alphanum_fraction": 0.6371740584, "num_tokens": 1373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810466522863, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7723358154065483}} {"text": "\n/**\n *\n * @file MatrixOperation.hpp\n * @brief matlab like functions\n * @author Naoki Takahashi\n *\n **/\n\n#pragma once\n\n#include \"Matrix.hpp\"\n\n#include \n#include \n\nnamespace Tools {\n\tnamespace Math {\n\t\ttemplate \n\t\tT norm(const Eigen::Matrix &matrix);\n\n\t\ttemplate \n\t\tEigen::Matrix diagonal(const Eigen::Matrix &vector);\n\t\ttemplate \n\t\tMatrixX diagonal(const VectorX &vector);\n\n\t\ttemplate \n\t\tT dot(const Eigen::Matrix &vector1, const Eigen::Matrix &vector2);\n\n\t\ttemplate \n\t\tEigen::Matrix cross(const Eigen::Matrix &vector1, const Eigen::Matrix &vector2);\n\t}\n}\n\n", "meta": {"hexsha": "74207a36efe2010fb656696bcab87c5510390ccd", "size": 821, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Tools/Math/MatrixOperation.hpp", "max_stars_repo_name": "NaokiTakahashi12/OpenHumanoidController", "max_stars_repo_head_hexsha": "ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-23T06:21:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-23T06:21:47.000Z", "max_issues_repo_path": "src/Tools/Math/MatrixOperation.hpp", "max_issues_repo_name": "NaokiTakahashi12/hc-early", "max_issues_repo_head_hexsha": "ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2019-07-30T00:17:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-09T23:00:43.000Z", "max_forks_repo_path": "src/Tools/Math/MatrixOperation.hpp", "max_forks_repo_name": "NaokiTakahashi12/OpenHumanoidController", "max_forks_repo_head_hexsha": "ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4571428571, "max_line_length": 112, "alphanum_fraction": 0.6784409257, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825847, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7722550734006615}} {"text": "#define BOOST_TEST_MAIN\r\n#include \r\n\r\n#include \"Vector.h\"\r\n\r\nBOOST_AUTO_TEST_CASE( CAN_ADD_TWO_VECTORS )\r\n{\r\n Vector3 v1{0.1f, 0.1f, 0.1f};\r\n Vector3 v2{0.2f, 0.2f, 0.2f};\r\n\r\n float expectedValue = 0.1f + 0.2f;\r\n\r\n Vector3 actualResult = v1 + v2;\r\n Vector3 expectedResult {expectedValue, expectedValue, expectedValue};\r\n\r\n BOOST_ASSERT(actualResult == expectedResult);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( CAN_SUBTRACT_TWO_VECTORS )\r\n{\r\n Vector3 v1{0.1f, 0.1f, 0.1f};\r\n Vector3 v2{0.2f, 0.2f, 0.2f};\r\n\r\n float expectedValue = 0.1f - 0.2f;\r\n\r\n Vector3 actualResult = v1 - v2;\r\n Vector3 expectedResult {expectedValue, expectedValue, expectedValue};\r\n\r\n BOOST_ASSERT(actualResult == expectedResult);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( CAN_MULTIPLY_TWO_VECTORS )\r\n{\r\n Vector3 v1{0.1f, 0.1f, 0.1f};\r\n Vector3 v2{0.2f, 0.2f, 0.2f};\r\n\r\n float expectedValue = 0.1f * 0.2f;\r\n\r\n Vector3 actualResult = v1 * v2;\r\n Vector3 expectedResult {expectedValue, expectedValue, expectedValue};\r\n\r\n BOOST_ASSERT(actualResult == expectedResult);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( CAN_SCALE_VECTORS )\r\n{\r\n Vector3 v1{0.1f, 0.1f, 0.1f};\r\n float scalar = 5.0f;\r\n\r\n float expectedValue = 0.1f * 5.0f;\r\n\r\n Vector3 actualResult = v1 * scalar;\r\n Vector3 actualResult2 = scalar * v1;\r\n Vector3 expectedResult {expectedValue, expectedValue, expectedValue};\r\n\r\n BOOST_ASSERT(actualResult == expectedResult);\r\n BOOST_ASSERT(actualResult2 == expectedResult);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( CAN_SCALE_VECTORS_MIXED )\r\n{\r\n Vector3 v1{0.1f, 0.1f, 0.1f};\r\n double scalar = 5.0;\r\n\r\n\r\n float expectedValue = 0.1f * 5.0f;\r\n\r\n Vector3 actualResult = v1 * scalar;\r\n Vector3 actualResult2 = scalar * v1;\r\n Vector3 expectedResult {expectedValue, expectedValue, expectedValue};\r\n\r\n BOOST_ASSERT(actualResult == expectedResult);\r\n BOOST_ASSERT(actualResult2 == expectedResult);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( CAN_CALCULATE_DOT )\r\n{\r\n Vector3 v1{0.1f, 0.0f, 0.0f};\r\n Vector3 v2{0.1f, 0.0f, 0.0f};\r\n\r\n float actualResult = dot(v1, v2);\r\n float actualResult2 = dot(v2, v1);\r\n float expectedResult = 0.1f * 0.1f;\r\n\r\n BOOST_ASSERT(actualResult == expectedResult);\r\n BOOST_ASSERT(actualResult2 == expectedResult);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( CAN_CALCULATE_CROSS )\r\n{\r\n Vector3 v1{0.1f, 0.1f, 0.1f};\r\n Vector3 v2{0.25f, 0.15f, 0.35f};\r\n\r\n Vector3 actualResult = cross(v1, v2);\r\n Vector3 expectedResult {0.02f, -0.01f, -0.01f};\r\n\r\n BOOST_ASSERT(actualResult == expectedResult);\r\n}", "meta": {"hexsha": "7ad815bd16b66b958c0ac6555ac04952d1b1489e", "size": 2742, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/VectorTests.cpp", "max_stars_repo_name": "engineerjames/weekend-raytracer", "max_stars_repo_head_hexsha": "dd203621d6dee154855d128949ded1c6a531e0da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/VectorTests.cpp", "max_issues_repo_name": "engineerjames/weekend-raytracer", "max_issues_repo_head_hexsha": "dd203621d6dee154855d128949ded1c6a531e0da", "max_issues_repo_licenses": ["MIT"], "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/VectorTests.cpp", "max_forks_repo_name": "engineerjames/weekend-raytracer", "max_forks_repo_head_hexsha": "dd203621d6dee154855d128949ded1c6a531e0da", "max_forks_repo_licenses": ["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.9795918367, "max_line_length": 81, "alphanum_fraction": 0.6710430343, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.7722550715305714}} {"text": "//\n// PolyfitBoost.hpp\n// Polyfit\n//\n// Created by Patrick Löber on 23.11.18.\n// Copyright © 2018 Patrick Loeber. All rights reserved.\n//\n// C++ implementation if polyfit using boost library. See also:\n// https://www.numpy.org/devdocs/reference/generated/numpy.polynomial.polynomial.polyfit.html\n// https://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.polyfit.html\n\n#include \n#include \n\n/*\n Finds the coefficients of a polynomial p(x) of degree n that fits the data,\n p(x(i)) to y(i), in a least squares sense. The result p is a row vector of\n length n+1 containing the polynomial coefficients in incremental powers.\n \n param:\n xValues x axis values\n yValues y axis values\n degree polynomial degree including the constant\n weights optional, weights to apply to the y-coordinates of the sample points\n \n return:\n coefficients of a polynomial starting at the constant coefficient and\n ending with the coefficient of power to degree.\n*/\ntemplate \nstd::vector polyfit_boost(const std::vector &xValues, const std::vector &yValues, const int degree, const std::vector& weights = std::vector())\n{\n using namespace boost::numeric::ublas;\n \n if (xValues.size() != yValues.size())\n throw std::invalid_argument(\"X and Y vector sizes do not match\");\n \n bool useWeights = weights.size() > 0 && weights.size() == xValues.size();\n \n // one more because of c0 coefficient\n int numCoefficients = degree + 1;\n \n size_t nCount = xValues.size();\n matrix X(nCount, numCoefficients);\n matrix Y(nCount, 1);\n \n // fill Y matrix\n for (size_t i = 0; i < nCount; i++)\n {\n if (useWeights)\n Y(i, 0) = yValues[i] * weights[i];\n else\n Y(i, 0) = yValues[i];\n }\n \n // fill X matrix (Vandermonde matrix)\n for (size_t nRow = 0; nRow < nCount; nRow++)\n {\n T nVal = 1.0f;\n for (int nCol = 0; nCol < numCoefficients; nCol++)\n {\n if (useWeights)\n X(nRow, nCol) = nVal * weights[nRow];\n else\n X(nRow, nCol) = nVal;\n nVal *= xValues[nRow];\n }\n }\n \n // transpose X matrix\n matrix Xt(trans(X));\n // multiply transposed X matrix with X matrix\n matrix XtX(prec_prod(Xt, X));\n // multiply transposed X matrix with Y matrix\n matrix XtY(prec_prod(Xt, Y));\n \n // lu decomposition\n permutation_matrix pert(XtX.size1());\n const std::size_t singular = lu_factorize(XtX, pert);\n // must be singular\n assert(singular == 0);\n \n // backsubstitution\n lu_substitute(XtX, pert, XtY);\n \n // copy the result to coeff\n return std::vector(XtY.data().begin(), XtY.data().end());\n}\n\n/*\n Calculates the value of a polynomial of degree n evaluated at x. The input\n argument coefficients is a vector of length n+1 whose elements are the coefficients\n in incremental powers of the polynomial to be evaluated.\n \n param:\n coefficients polynomial coefficients generated by polyfit() function\n xValues x axis values\n \n return:\n Fitted Y values.\n*/\ntemplate\nstd::vector polyval( const std::vector& coefficients, const std::vector& xValues )\n{\n size_t nCount = xValues.size();\n size_t nDegree = coefficients.size();\n std::vector yValues( nCount );\n \n for (size_t i = 0; i < nCount; i++ )\n {\n T yVal = 0;\n T xPowered = 1;\n T xVal = xValues[i];\n for (size_t j = 0; j < nDegree; j++ )\n {\n // multiply current x by coefficient\n yVal += coefficients[j] * xPowered;\n // power up the X\n xPowered *= xVal;\n }\n yValues[i] = yVal;\n }\n \n return yValues;\n}\n", "meta": {"hexsha": "83e60cbed7249c482afbb01a693662c9f12b6d87", "size": 3853, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PolyfitBoost.hpp", "max_stars_repo_name": "jcmayoral/Polyfit", "max_stars_repo_head_hexsha": "956286d368cb377df81a5ea1eca5d2ff8e8fdb3a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2019-06-21T09:51:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T23:53:46.000Z", "max_issues_repo_path": "PolyfitBoost.hpp", "max_issues_repo_name": "jcmayoral/Polyfit", "max_issues_repo_head_hexsha": "956286d368cb377df81a5ea1eca5d2ff8e8fdb3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-02T06:20:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-03T09:08:22.000Z", "max_forks_repo_path": "PolyfitBoost.hpp", "max_forks_repo_name": "jcmayoral/Polyfit", "max_forks_repo_head_hexsha": "956286d368cb377df81a5ea1eca5d2ff8e8fdb3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2020-04-11T15:46:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T01:43:30.000Z", "avg_line_length": 30.5793650794, "max_line_length": 158, "alphanum_fraction": 0.6182195692, "num_tokens": 1016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7722550660029546}} {"text": "#ifndef __PROXIMALS__\n#define __PROXIMALS__\n\n#include \n#include \n\nnamespace proxopp\n{\nclass proxOperator\n{\npublic:\n\tproxOperator() {}\n\tvirtual ~proxOperator() {}\n\n\tvirtual float f(Eigen::VectorXf& x)\n\t{\n\t\t// f(x)\n\t\treturn 0.0f;\n\t}\n\n\tvirtual Eigen::VectorXf operator()(Eigen::VectorXf& x, float lambda)\n\t{\n\t\t// prox_{\\lambda f}(x)\n\t\treturn x;\n\t}\n\n\tvirtual Eigen::VectorXf operator()(Eigen::VectorXf& x)\n\t{\n\t\t(*this)(x, 1.0); \n\t}\n\n\tvirtual Eigen::VectorXf prox(Eigen::VectorXf& x, float lambda)\n\t{\n\t\treturn (*this)(x, lambda);\n\t}\n};\n\n//\tThe proximal operator of the L1 norm\n//\tsoft_thresholding(x,lambda) = sign(x)*max(|x| - lambda, 0) (element-wise)\n\nclass softThresholdingOperator : public proxOperator\n{\npublic:\n\tfloat f(Eigen::VectorXf& x) override\n\t{\n\t\treturn x.lpNorm<1>();\n\t}\n\n\tEigen::VectorXf operator()(Eigen::VectorXf& x, float lambda) override\n\t{\n\t\treturn x.array().sign()*((x.array().abs()-lambda).max(Eigen::ArrayXf::Zero(x.rows())));\n\t}\n};\n\n//\tThe proximal operator of the (convex) indicator\n//\tfunction of the set {x | Ax = b} is\n//\tx - At(AtA)^(-1)(Ax - b)\n\nclass proxLinearEquality : public proxOperator\n{\npublic:\n\tproxLinearEquality(Eigen::MatrixXf& A, Eigen::VectorXf& b) : _A(A), _b(b)\n\t{\n\t\t_Q = A.transpose()*((A*A.transpose()).inverse());\n\t\t_Qb = _Q*_b;\n\t\t_QA = _Q*_A;\n\t}\n\n\tfloat f(Eigen::VectorXf& x) override\n\t{\n\t\tif((_A*x - _b).norm() < tol)\n\t\t{\n\t\t\treturn 0;\n\t\t} else {\n\t\t\treturn std::numeric_limits::max();\n\t\t}\n\t}\n\n\tEigen::VectorXf operator()(Eigen::VectorXf& x, float lambda) override\n\t{\n\t\treturn (x - _QA*x + _Qb);\n\t}\nprivate:\n\tEigen::MatrixXf _A;\n\tEigen::MatrixXf _b;\n\tEigen::MatrixXf _Q;\n\tEigen::MatrixXf _QA;\n\tEigen::VectorXf _Qb;\n\n\tconst double tol = 1e-6;\n};\n\n//\tProximal operator of the squared L2 norm\n\nclass proximalL2Square : public proxOperator\n{\npublic:\n\tfloat f(Eigen::VectorXf& x) override\n\t{\n\t\treturn x.squaredNorm();\n\t}\n\n\tEigen::VectorXf operator()(Eigen::VectorXf& x, float lambda) override\n\t{\n\t\treturn x/(1.0f+lambda);\n\t}\n};\n\n//\tProximal operator of euclidean norm\n//\tBlock thresholding\n\nclass proximalL2 : public proxOperator\n{\npublic:\n\tfloat f(Eigen::VectorXf& x)\n\t{\n\t\treturn x.lpNorm<2>();\n\t}\n\n\tEigen::VectorXf operator()(Eigen::VectorXf& x, float lambda)\n\t{\n\t\tconst float norm2 = x.lpNorm<2>();\n\n\t\tif(lambda > norm2) return Eigen::VectorXf::Zero(x.rows());\n\n\t\treturn x*(1 - lambda / norm2);\n\t}\n};\n\n//\tPROJECTION ON BALLS\n\n//\tProjector onto L2 ball\n\nclass proximalL2Ball : public proxOperator\n{\npublic:\n\tproximalL2Ball(float lambda) : radius(lambda) {}\n\n\tfloat f(Eigen::VectorXf& x)\n\t{\n\t\treturn x.lpNorm<2>() <= radius ? 0 : std::numeric_limits::max();\n\t}\n\n\tEigen::VectorXf operator()(Eigen::VectorXf& x, float lambda = 0.0)\n\t{\n\t\tfloat norm2 = x.lpNorm<2>(); \n\n\t\tif(norm2 == 0.0f) \n\t\t\treturn Eigen::VectorXf::Zero(x.rows()); \n\t\t\t \n\t\treturn x*radius/x.lpNorm<2>();\n\t}\nprivate:\n\tfloat radius;\n};\n\n//\tFast Projection onto the L1 Ball using sorting\n//\tUsing algorithm from\n//\tHeld, M., Wolfe, P., Crowder, H.: Validation of subgradient optimization.\n//\tMathematical Programming6, 62–88 (1974)\n\n//\tAlternatively, see Condat, L.\n// \tFast Projection onto the Simplex and the L1-Ball\n//\thttps://www.gipsa-lab.grenoble-inp.fr/~laurent.condat/publis/Condat_simplexproj.pdf\n//\tIt corresponds to Algorithm 1\n\nclass proximalL1Ball : public proxOperator\n{\npublic:\n\tproximalL1Ball(float lambda) : radius(lambda) {}\n\n\tfloat f(Eigen::VectorXf& x)\n\t{\n\t\treturn (x.lpNorm<1>() < radius) ? 0 : std::numeric_limits::max();\n\t}\n\n\tEigen::VectorXf operator()(Eigen::VectorXf& x, float lambda = 0.0f)\n\t{\n\t\tif(x.lpNorm<1>() < radius) return x;\n\n\t\tEigen::ArrayXf u = Eigen::ArrayXf(x.array().abs());\n\t\tstd::sort(u.data(), u.data()+u.size(), std::greater());\n\n\t\tint k=1, K=1;\n\t\tfloat tau = 0.0f;\n\n\t\tfor(k=1;k<=x.rows();k++)\n\t\t{\n\t\t\tfloat mean = 0.0f;\n\n\t\t\tfor(int i = 0; i < k; i++)\n\t\t\t{\n\t\t\t\tmean += u[i];\n\t\t\t}\n\t\t\tmean = (mean-radius)/k;\n\n\t\t\tif(mean < u[k-1])\n\t\t\t{\n\t\t\t\tK \t= k-1;\n\t\t\t\ttau = mean;\n\t\t\t}\n\t\t}\n\t\tstd::cout << tau << std::endl;\n\n\t\tEigen::VectorXf xtau = x.array().abs()-tau*Eigen::ArrayXf::Ones(x.rows());\n\t\treturn x.array().sign()*(xtau).array().max(Eigen::VectorXf::Zero(x.rows()).array());\n\t}\nprivate:\n\tfloat radius;\n};\n\n//\tProximal operator of the indicator function of\n//\tthe set {x | max abs(x_i) <= lambda} (Linf ball)\n\nclass proximalLinfBall : public proxOperator\n{\npublic:\n\tproximalLinfBall(float lambda) : radius(lambda) {}\n\n\tfloat f(Eigen::VectorXf& x) override\n\t{\n\t\treturn (x.lpNorm() < radius) ? 0 : std::numeric_limits::max();\n\t}\n\n\tEigen::VectorXf operator()(Eigen::VectorXf& x, float lambda = 0.0f) override\n\t{\n\t\tfor(int i = 0; i < x.rows(); i++)\n\t\t{\n\t\t\tif(x[i] > radius) \tx[i] = radius;\n\t\t\tif(x[i] < -radius) \tx[i] = -radius;\n\t\t}\n\t}\nprivate:\n\tfloat radius;\n};\n\n//\tProjection on the intersection of L1 and Linf balls\n//\twith binary search\n\nclass proximalL1LinfBall : public proxOperator\n{\npublic:\n\tproximalL1LinfBall(float radius_l1, float radius_linf) : r_l1(radius_l1),\n\tr_linf(radius_linf)\n\t{}\n\n\tfloat f(Eigen::VectorXf& x)\n\t{\n\t\tif(x.lpNorm<1>()() < r_linf) return 0.0f;\n\t\treturn std::numeric_limits::max();\n\t}\n\n\tEigen::VectorXf operator()(Eigen::VectorXf& x)\n\t{\n\t\tint n = x.rows();\n\t\tproximalLinfBall projLinf(r_linf);\n\t\tEigen::VectorXf y = projLinf(x);\n\n\t\tif(y.lpNorm<1>() < r_l1) return y;\n\n\t\tconst double eps = 1e-6;\n\t\tconst int itermax = 50;\n\t\tint k = 0;\n\t\tfloat nu_l = 0.0f;\n\t\tfloat nu_r = x.array().abs().maxCoeff();\n\t\tEigen::ArrayXf z1,z2;\n\n\t\twhile((k < itermax) && (nu_l - nu_r > eps))\n\t\t{\n\t\t\tfloat nu_m = 0.5*(nu_l+nu_r);\n\n\t\t\tz1 = y.array().abs()-nu_m*Eigen::ArrayXf::Ones(n);\n\t\t\tz1 = z1.max(Eigen::ArrayXf::Zero(n));\n\t\t\tz2 = z1.min(r_linf*Eigen::ArrayXf::Ones(n));\n\n\t\t\tif(z2.lpNorm<1>() < r_l1)\n\t\t\t{\n\t\t\t\tnu_r = nu_m;\n\t\t\t} else {\n\t\t\t\tnu_l = nu_m;\n\t\t\t}\n\n\t\t\tk++;\n\t\t}\n\n\t\treturn z2*x.array().sign();\n\t}\nprivate:\n\tfloat r_l1; // radius of L1 ball\n\tfloat r_linf; // radius of Linf ball (max coeff of abs values)\n};\n\n} // namespace proxopp\n\n#endif\n", "meta": {"hexsha": "24157ab17d2f7b255d8906b99fc41c3f188b21a2", "size": 6007, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/proximals.hpp", "max_stars_repo_name": "jopago/proxopp", "max_stars_repo_head_hexsha": "4eef17219f99591850bfbca26da2a4baf7e7268b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-17T21:20:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-17T21:20:15.000Z", "max_issues_repo_path": "include/proximals.hpp", "max_issues_repo_name": "jopago/proxopp", "max_issues_repo_head_hexsha": "4eef17219f99591850bfbca26da2a4baf7e7268b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/proximals.hpp", "max_forks_repo_name": "jopago/proxopp", "max_forks_repo_head_hexsha": "4eef17219f99591850bfbca26da2a4baf7e7268b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-11T21:04:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-11T21:04:38.000Z", "avg_line_length": 20.2939189189, "max_line_length": 89, "alphanum_fraction": 0.6407524555, "num_tokens": 2058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642018, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7722089086053321}} {"text": "#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\n\nvoid main() {\n\n\t{\n\t\tEigen::Matrix2d mat;\n\t\tmat << 1, 2,\n\t\t\t3, 4;\n\t\tcout << \"mat: \\n\" << mat << endl;\n\t\tcout << \"Here is mat.sum(): \" << mat.sum() << endl;\n\t\tcout << \"Here is mat.prod(): \" << mat.prod() << endl;\n\t\tcout << \"Here is mat.mean(): \" << mat.mean() << endl;\n\t\tcout << \"Here is mat.minCoeff(): \" << mat.minCoeff() << endl;\n\t\tcout << \"Here is mat.maxCoeff(): \" << mat.maxCoeff() << endl;\n\t\tcout << \"Here is mat.trace(): \" << mat.trace() << endl;\n\t}\n\t{\n\t\tVectorXf v(2);\n\t\tMatrixXf m(2, 2), n(2, 2);\n\n\t\tv << -1,\n\t\t\t2;\n\n\t\tm << 1, -2,\n\t\t\t-3, 4;\n\t\tcout << \"v.squaredNorm() = \" << v.squaredNorm() << endl;\n\t\tcout << \"v.norm() = \" << v.norm() << endl;\n\t\tcout << \"v.lpNorm<1>() = \" << v.lpNorm<1>() << endl;\n\t\tcout << \"v.lpNorm<2>() = \" << v.lpNorm<2>() << endl;\n\t\tcout << \"v.lpNorm() = \" << v.lpNorm() << endl;\n\t\tcout << endl;\n\t\tcout << \"m.squaredNorm() = \" << m.squaredNorm() << endl;\n\t\tcout << \"m.norm() = \" << m.norm() << endl;\n\t\tcout << \"m.lpNorm<1>() = \" << m.lpNorm<1>() << endl;\n\t\tcout << \"m.lpNorm<2>() = \" << m.lpNorm<2>() << endl;\n\t\tcout << \"m.lpNorm() = \" << m.lpNorm() << endl;\n\t}\n\t{\n\t\tMatrixXf m(2, 2);\n\t\tm << 1, -2, -3, 4;\n\t\tcout << \"1-norm(m) = \" << m.cwiseAbs().colwise().sum().maxCoeff() << \" == \" <<\n\t\t\tm.colwise().lpNorm<1>().maxCoeff() << endl;\n\t\tcout << \"infty-norm(m) = \" << m.cwiseAbs().rowwise().sum().maxCoeff()\n\t\t\t<< \" == \" << m.rowwise().lpNorm<1>().maxCoeff() << endl;\n\t}\n\n\t{\n\t\tArrayXXf a(2, 2);\n\n\t\ta << 1, 2,\n\t\t\t3, 4;\n\t\tcout << \"(a > 0).all() = \" << (a > 0).all() << endl;\n\t\tcout << \"(a > 0).any() = \" << (a > 0).any() << endl;\n\t\tcout << \"(a > 0).count() = \" << (a > 0).count() << endl;\n\t\tcout << endl;\n\t\tcout << \"(a > 2).all() = \" << (a > 2).all() << endl;\n\t\tcout << \"(a > 2).any() = \" << (a > 2).any() << endl;\n\t\tcout << \"(a > 2).count() = \" << (a > 2).count() << endl;\n\t}\n\t\n\t{\n\t\t// Visitors\n\t\tEigen::MatrixXf m(2, 2);\n\n\t\tm << 1, 2,\n\t\t\t4, 4;\n\t\t//get location of maximum\n\t\tMatrixXf::Index maxRow, maxCol;\n\t\tfloat max = m.maxCoeff(&maxRow, &maxCol);\n\t\t//get location of minimum\n\t\tMatrixXf::Index minRow, minCol;\n\t\tfloat min = m.minCoeff(&minRow, &minCol);\n\t\tcout << \"Max: \" << max << \", at: \" <<\n\t\t\tmaxRow << \",\" << maxCol << endl;\n\t\tcout << \"Min: \" << min << \", at: \" <<\n\t\t\tminRow << \",\" << minCol << endl;\n\t}\n\t{\n\t\tEigen::MatrixXf mat(2, 4);\n\t\tmat << 1, 2, 6, 9,\n\t\t\t 3, 1, 7, 2;\n\t\tcout << \"column's maximum : \" << endl;\n\t\tcout << mat.colwise().maxCoeff() << endl;\n\t}\n\t{\n\t\tEigen::MatrixXf mat(2, 4);\n\t\tEigen::VectorXf v(2);\n\n\t\tmat << 1, 2, 6, 9,\n\t\t\t 3, 1, 7, 2;\n\t\tv << 0, \n\t\t\t 1;\n\t\t// add v to each column of m\n\t\tmat.colwise() += v;\n\t\tcout << \"Broadcasting colwise: \\n\" << mat << endl;\n\n\t\tEigen::VectorXf w(4);\n\t\tw << 0, 1, 2, 3;\n\n\t\tmat.rowwise() += w.transpose();\n\n\t\tcout << \"Broadcasting rowwise: \\n\" << mat << endl;\n\t}\n\t{\n\t\tEigen::MatrixXf m(2, 4);\n\t\tEigen::VectorXf v(2);\n\t\tm << 1, 23, 6, 9,\n\t\t\t 3, 11, 7, 2;\n\t\tv << 2,\n\t\t\t 3;\n\t\tMatrixXf::Index index;\n\t\t// find nearest neighbour\n\t\t(m.colwise() - v).colwise().squaredNorm().minCoeff(&index);\n\t\tcout << \"Nearest neighbour is column \" << index << \":\" << endl;\n\t\tcout << m.col(index) << endl;\n\n\t}\n\tsystem(\"pause\");\n}", "meta": {"hexsha": "ced66fa22dfa611daa9255e21557062bdd71f80a", "size": 3259, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/eigen/eigen/reductions_visitors_broadcasting/reductions_visitors_broadcasting.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/reductions_visitors_broadcasting/reductions_visitors_broadcasting.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/reductions_visitors_broadcasting/reductions_visitors_broadcasting.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": 26.2822580645, "max_line_length": 80, "alphanum_fraction": 0.4832770789, "num_tokens": 1281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.8688267881258485, "lm_q1q2_score": 0.7721774582084889}} {"text": "#include \n#include \n#include \n\nusing namespace arma;\nusing namespace std;\n\nclass Conjunto {\npublic:\n\tvirtual double membresia(double x) const = 0;\n\tvirtual void graficar(Gnuplot& gp, double escala = 1) const = 0;\n\tvirtual double centroide_x() const = 0;\n\tvirtual double area(double altura) const = 0;\n};\n\nclass ConjuntoTrapezoidal : public Conjunto {\npublic:\n\tConjuntoTrapezoidal(vec puntos);\n\n\tdouble membresia(double x) const override;\n\tvoid graficar(Gnuplot& gp, double escala = 1) const override;\n\tdouble centroide_x() const override;\n\tdouble area(double altura) const override;\n\n\tconst double a, b, c, d;\n};\n\nclass ConjuntoGaussiano : public Conjunto {\npublic:\n\tConjuntoGaussiano(double t_media, double t_sigma);\n\n\tdouble membresia(double x) const override;\n\tvoid graficar(Gnuplot& gp, double escala = 1) const override;\n\tdouble centroide_x() const override;\n\tdouble area(double altura) const override;\n\tconst double media, sigma;\n};\n\nenum class tipoConjunto {\n trapezoidal,\n gaussiano\n};\n\nclass SistemaBorroso {\npublic:\n\tSistemaBorroso(const mat& matrizEntrada,\n\t tipoConjunto tipoEntrada);\n\tSistemaBorroso(const mat& matrizEntrada,\n\t tipoConjunto tipoEntrada,\n\t const mat& matrizSalida,\n\t tipoConjunto tipoSalida,\n\t const uvec& t_reglasMapeo = {});\n\n\tvec activacionesEntrada(double x) const;\n\tvec mapeoEntradaSalida(const vec& activacionesEntrada) const;\n\tdouble defuzzyficarSalida(vec activaciones) const;\n\tdouble salidaSistema(double entrada) const;\n\n const vector>& conjuntosEntrada() const { return m_conjuntosEntrada; };\n const vector>& conjuntosSalida() const { return m_conjuntosSalida; };\n\nprivate:\n vector> m_conjuntosEntrada;\n vector> m_conjuntosSalida;\n const uvec m_reglasMapeo;\n};\n\nConjuntoTrapezoidal::ConjuntoTrapezoidal(vec puntos)\n : a{puntos(0)}\n , b{puntos(1)}\n , c{puntos(2)}\n , d{puntos(3)}\n{\n\t// chequear orden de puntos\n\tif (!puntos.is_sorted())\n\t\tthrow runtime_error(\"los puntos no estan ordenados\");\n\n\tif (puntos.n_elem != 4)\n\t\tthrow runtime_error(\"no se tienen cuatro puntos\");\n}\n\ndouble ConjuntoTrapezoidal::membresia(double x) const\n{\n\tif (x < a or x > d)\n\t\treturn 0;\n\telse if (a <= x and x < b)\n\t\treturn (x - a) / (b - a);\n\telse if (b <= x and x <= c)\n\t\treturn 1;\n\telse if (c < x and x <= d)\n\t\treturn 1 - (x - c) / (d - c);\n\telse\n throw runtime_error(\"Nunca se debería llegar acá (en ConjuntoTrapezoidal::membresia)\");\n}\n\nvoid ConjuntoTrapezoidal::graficar(Gnuplot& gp, double escala) const\n{\n\tconst mat puntos = {{a, 0},\n\t {b, 1 * escala},\n\t {c, 1 * escala},\n\t {d, 0}};\n\n\tgp << gp.file1d(puntos) << \"with lines\";\n}\n\ndouble ConjuntoTrapezoidal::centroide_x() const\n{\n\t// Ver http://www.efunda.com/math/areas/Trapezoid.cfm\n\tconst double A = c - b;\n\tconst double B = d - a;\n\tconst double C = b - a;\n\n\tconst double numerador = 2 * A * C\n\t + A * A\n\t + C * B\n\t + A * B\n\t + B * B;\n\tconst double denominador = 3 * (A + B);\n\tconst double result = numerador / denominador;\n\n\t// El resultado está como si el trapezoide tuviera el punto\n\t// a en (0, 0).\n\t// Para corregir esto, hace falta sumarle a.\n\n\treturn result + a;\n}\n\ndouble ConjuntoTrapezoidal::area(double altura) const\n{\n\treturn ((d - a) + (c - b)) * altura / 2;\n}\n\nConjuntoGaussiano::ConjuntoGaussiano(double t_media, double t_sigma)\n : media{t_media}\n , sigma{t_sigma}\n{\n\tif (t_sigma <= 0)\n\t\tthrow runtime_error(\"el sigma debe ser mayor o igual a cero\");\n}\n\ndouble ConjuntoGaussiano::membresia(double x) const\n{\n\treturn exp(-0.5 * (pow((x - media) / sigma, 2)));\n}\n\nvoid ConjuntoGaussiano::graficar(Gnuplot& gp, double escala) const\n{\n\tconst string exponencial = to_string(escala)\n\t + \" * exp(-0.5 * ((x - \"\n\t + to_string(media)\n\t + \") / \"\n\t + to_string(sigma)\n\t + \") ** 2)\";\n\n\tgp << exponencial << \"with lines\";\n}\n\ndouble ConjuntoGaussiano::centroide_x() const\n{\n\treturn media;\n}\n\ndouble ConjuntoGaussiano::area(double altura) const\n{\n\t// PREGUNTAR:\n\t// ¿Se puede escalar el área original de la gaussiana\n\t// por el grado de activación y obtener el área correcta?\n\treturn sigma * sqrt(2 * datum::pi) * altura;\n}\n\nvector> parsearTrapecios(const mat& matrizConjuntos)\n{\n vector> result;\n\n\tfor (unsigned int i = 0; i < matrizConjuntos.n_rows; ++i) {\n\t\tresult.push_back(unique_ptr{new ConjuntoTrapezoidal{matrizConjuntos.row(i).t()}});\n\t}\n\n\treturn result;\n}\n\nvector> parsearGaussianas(const mat& matrizConjuntos)\n{\n\tif (matrizConjuntos.n_cols != 2)\n\t\tthrow runtime_error(\"La matriz debe tener dos columnas\");\n\n vector> result;\n\n\tfor (unsigned int i = 0; i < matrizConjuntos.n_rows; ++i) {\n\t\tresult.push_back(unique_ptr{\n\t\t new ConjuntoGaussiano{matrizConjuntos(i, 0),\n\t\t matrizConjuntos(i, 1)}});\n\t}\n\n\treturn result;\n}\n\n// NOTA\n// Después de usar esta función hace falta cerrar el ploteo\n// ya sea ploteando algo más, o ploteando \"NaN notitle\".\nvoid graficarConjuntos(const vector>& conjuntos,\n Gnuplot& gp,\n vec escalas = {})\n{\n\tif (escalas.empty())\n\t\tescalas = ones(conjuntos.size());\n\n\tgp << \"plot \";\n\n\tfor (unsigned int i = 0; i < conjuntos.size(); ++i) {\n\t\tconjuntos[i]->graficar(gp, escalas(i));\n\t\tgp << \" title 'Conjunto \" << (i + 1) << \"', \";\n\t}\n}\n\nSistemaBorroso::SistemaBorroso(const mat& matrizEntrada, tipoConjunto tipoEntrada)\n{\n\tswitch (tipoEntrada) {\n\tcase tipoConjunto::trapezoidal:\n m_conjuntosEntrada = parsearTrapecios(matrizEntrada);\n\t\tbreak;\n\n\tcase tipoConjunto::gaussiano:\n m_conjuntosEntrada = parsearGaussianas(matrizEntrada);\n\t\tbreak;\n\t}\n}\n\nSistemaBorroso::SistemaBorroso(const mat& matrizEntrada,\n tipoConjunto tipoEntrada,\n const mat& matrizSalida,\n tipoConjunto tipoSalida,\n const uvec& t_reglasMapeo)\n : m_reglasMapeo{t_reglasMapeo}\n{\n\tswitch (tipoEntrada) {\n\tcase tipoConjunto::trapezoidal:\n m_conjuntosEntrada = parsearTrapecios(matrizEntrada);\n\t\tbreak;\n\n\tcase tipoConjunto::gaussiano:\n m_conjuntosEntrada = parsearGaussianas(matrizEntrada);\n\t\tbreak;\n\t}\n\n\tswitch (tipoSalida) {\n\tcase tipoConjunto::trapezoidal:\n m_conjuntosSalida = parsearTrapecios(matrizSalida);\n\t\tbreak;\n\n\tcase tipoConjunto::gaussiano:\n m_conjuntosSalida = parsearGaussianas(matrizSalida);\n\t\tbreak;\n\t}\n\n\tif (!t_reglasMapeo.empty()) {\n if (t_reglasMapeo.n_elem != m_conjuntosEntrada.size())\n\t\t\tthrow runtime_error(\n \"La cantidad de reglas tiene que ser la misma \"\n \"que la cantidad de conjuntos de entrada\");\n\n\t\tif (unique(t_reglasMapeo).eval().n_elem != t_reglasMapeo.n_elem)\n\t\t\tthrow runtime_error(\n \"No puede haber reglas que mapeen al mismo \"\n \"conjunto de salida\");\n\n if (max(t_reglasMapeo) != m_conjuntosSalida.size()\n\t\t || min(t_reglasMapeo != 1))\n\t\t\tthrow runtime_error(\n \"Los valores de las reglas están fuera de rango\");\n\t}\n}\n\nvec SistemaBorroso::activacionesEntrada(double x) const\n{\n vec result(m_conjuntosEntrada.size());\n\n for (unsigned int i = 0; i < m_conjuntosEntrada.size(); ++i) {\n result(i) = m_conjuntosEntrada[i]->membresia(x);\n }\n\n\treturn result;\n}\n\nvec SistemaBorroso::mapeoEntradaSalida(const vec& activacionesEntrada) const\n{\n if (m_reglasMapeo.empty())\n\t\tthrow runtime_error(\"No se tienen reglas de mapeo\");\n\n vec activacionesSalida(m_conjuntosSalida.size());\n\n for (unsigned int i = 0; i < m_reglasMapeo.n_elem; ++i) {\n\t\t// El \"- 1\" es para pasar el vector de reglas de mapeo de base 1 a base 0\n activacionesSalida(m_reglasMapeo(i) - 1) = activacionesEntrada(i);\n }\n\n\treturn activacionesSalida;\n}\n\ndouble SistemaBorroso::defuzzyficarSalida(vec activaciones) const\n{\n if (activaciones.size() != m_conjuntosSalida.size())\n\t\tthrow runtime_error(\n \"La cantidad de activaciones y la cantidad \"\n \"de conjuntos de salida no coinciden\");\n\n\tdouble numerador = 0, denominador = 0;\n\n for (unsigned int i = 0; i < m_conjuntosSalida.size(); ++i) {\n numerador += m_conjuntosSalida[i]->centroide_x()\n * m_conjuntosSalida[i]->area(activaciones(i));\n denominador += m_conjuntosSalida[i]->area(activaciones(i));\n\t}\n\n\treturn numerador / denominador;\n}\n\ndouble SistemaBorroso::salidaSistema(double entrada) const\n{\n\tconst vec actEntrada = activacionesEntrada(entrada);\n\tconst vec actSalida = mapeoEntradaSalida(actEntrada);\n\tconst double salida = defuzzyficarSalida(actSalida);\n\n\treturn salida;\n}\n", "meta": {"hexsha": "b1d7a60be832fc35da13234fff320166368a1ad5", "size": 9066, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "guia3/borroso.cpp", "max_stars_repo_name": "junrrein/ic2017", "max_stars_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "guia3/borroso.cpp", "max_issues_repo_name": "junrrein/ic2017", "max_issues_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "guia3/borroso.cpp", "max_forks_repo_name": "junrrein/ic2017", "max_forks_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8098159509, "max_line_length": 96, "alphanum_fraction": 0.6543128171, "num_tokens": 2608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7721254110723921}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\nint main()\n{\n constexpr otf::FunctionType type = otf::FunctionType::Rosenbrock;\n constexpr int num_dims = 10;\n\n std::srand(static_cast(std::time(nullptr)));\n\n const Eigen::VectorXd x_init = Eigen::VectorXd::Random(num_dims);\n const auto f = [](const Eigen::VectorXd& x) { return otf::GetValue(x, type); };\n const auto g = [](const Eigen::VectorXd& x) { return otf::GetGrad(x, type); };\n\n const Eigen::VectorXd lower_bound; // Empty vector indicates no lower bound constraint\n const Eigen::VectorXd upper_bound; // Empty vector indicates no upper bound constraint\n\n constexpr double epsilon = 1e-12;\n constexpr double default_alpha = 1e-01;\n constexpr int max_num_iters = 100000;\n\n Eigen::VectorXd x_star;\n unsigned num_iters;\n mathtoolbox::optimization::RunGradientDescent(\n x_init, f, g, lower_bound, upper_bound, epsilon, default_alpha, max_num_iters, x_star, num_iters);\n\n const Eigen::VectorXd expected_solution = otf::GetSolution(num_dims, type);\n const double expected_value = otf::GetValue(expected_solution, type);\n const double initial_value = otf::GetValue(x_init, type);\n const double found_value = otf::GetValue(x_star, type);\n\n std::cout << \"#iterations: \" << num_iters << std::endl;\n std::cout << \"Initial solution: \" << x_init.transpose() << \" (\" << initial_value << \")\" << std::endl;\n std::cout << \"Found solution: \" << x_star.transpose() << \" (\" << found_value << \")\" << std::endl;\n std::cout << \"Expected solution: \" << expected_solution.transpose() << \" (\" << expected_value << \")\" << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "5b65bec241a8d86112bb24a45ed917986a2ee979", "size": 1887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/gradient-descent/main.cpp", "max_stars_repo_name": "yuki-koyama/mathtoolbox", "max_stars_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 195.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T16:12:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:52:56.000Z", "max_issues_repo_path": "examples/gradient-descent/main.cpp", "max_issues_repo_name": "amazing89/mathtoolbox", "max_issues_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2018-04-15T01:24:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T09:14:23.000Z", "max_forks_repo_path": "examples/gradient-descent/main.cpp", "max_forks_repo_name": "amazing89/mathtoolbox", "max_forks_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T04:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:28:12.000Z", "avg_line_length": 43.8837209302, "max_line_length": 118, "alphanum_fraction": 0.6438791733, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.7720804427492128}} {"text": "// -*- coding: utf-16 -*-\n#pragma once\n\n/*! @file include/fractions.hpp\n * This is a C++ Library header.\n */\n\n#include \n// #include \n#include \"common_concepts.h\"\n#include \n#include \n#include \n\nnamespace fun\n{\n\n/**\n * @brief absolute (for unsigned)\n * \n * @tparam T \n * @param a \n * @return T \n */\ntemplate \nrequires std::is_unsigned_v\ninline constexpr auto abs(const T& a) -> T\n{\n return a;\n}\n\n/**\n * @brief absolute\n * \n * @tparam T \n */\ntemplate \nrequires (!std::is_unsigned_v && ordered_ring)\ninline constexpr auto abs(const T& a) -> T\n{\n return (a < T(0)) ? -a : a;\n}\n\n\n/*!\n * @brief Greatest common divider\n *\n * @tparam _Mn\n * @param[in] __m\n * @param[in] __n\n * @return _Mn\n */\ntemplate \ninline constexpr auto gcd_recur(_Mn __m, _Mn __n) -> _Mn\n{\n if (__n == 0)\n {\n return abs(__m);\n }\n return gcd_recur(__n, __m % __n);\n}\n\n/*!\n * @brief Greatest common divider\n *\n * @tparam _Mn\n * @param[in] __m\n * @param[in] __n\n * @return _Mn\n */\ntemplate \ninline constexpr auto gcd(_Mn __m, _Mn __n) -> _Mn\n{\n if (__m == 0)\n {\n return abs(__n);\n }\n return gcd_recur(__m, __n);\n}\n\n/*!\n * @brief Least common multiple\n *\n * @tparam _Mn\n * @param[in] __m\n * @param[in] __n\n * @return _Mn\n */\ntemplate \ninline constexpr auto lcm(_Mn __m, _Mn __n) -> _Mn\n{\n if (__m == 0 || __n == 0)\n {\n return 0;\n }\n return (abs(__m) / gcd(__m, __n)) * abs(__n);\n}\n\n\ntemplate \nstruct Fraction : boost::totally_ordered,\n boost::totally_ordered2, Z,\n boost::multipliable2, Z,\n boost::dividable2, Z>>>>\n{\n Z _num;\n Z _den;\n\n\n /*!\n * @brief Construct a new Fraction object\n *\n * @param[in] num\n * @param[in] den\n */\n constexpr Fraction(Z num, Z den)\n : _num {std::move(num)}\n , _den {std::move(den)}\n {\n this->normalize();\n }\n\n constexpr void normalize()\n {\n Z common = gcd(this->_num, this->_den);\n if (common == Z(1) || common == Z(0))\n {\n return;\n }\n if (this->_den < Z(0))\n {\n common = -common;\n }\n this->_num /= common;\n this->_den /= common;\n }\n\n /*!\n * @brief Construct a new Fraction object\n *\n * @param[in] num\n */\n constexpr explicit Fraction(Z&& num)\n : _num {std::move(num)}\n , _den(Z(1))\n {\n }\n\n /*!\n * @brief Construct a new Fraction object\n *\n * @param[in] num\n */\n constexpr explicit Fraction(const Z& num)\n : _num {num}\n , _den(1)\n {\n }\n\n /*!\n * @brief Construct a new Fraction object\n *\n * @param[in] num\n */\n constexpr Fraction()\n : _num(0)\n , _den(1)\n {\n }\n\n /*!\n * @brief\n *\n * @return const Z&\n */\n [[nodiscard]] constexpr auto num() const noexcept -> const Z&\n {\n return _num;\n }\n\n /*!\n * @brief\n *\n * @return const Z&\n */\n [[nodiscard]] constexpr auto den() const noexcept -> const Z&\n {\n return _den;\n }\n\n /*!\n * @brief\n *\n * @return Fraction\n */\n [[nodiscard]] constexpr auto abs() const -> Fraction\n {\n return Fraction(abs(this->_num), abs(this->_den));\n }\n\n /*!\n * @brief\n *\n */\n constexpr void reciprocal() noexcept(std::is_nothrow_swappable_v)\n {\n std::swap(this->_num, this->_den);\n }\n\n /*!\n * @brief\n *\n * @return Fraction\n */\n constexpr auto operator-() const -> Fraction\n {\n auto res = Fraction(*this);\n res._num = -res._num;\n return res;\n }\n\n /*!\n * @brief\n *\n * @param[in] frac\n * @return Fraction\n */\n constexpr auto operator+(const Fraction& frac) const -> Fraction\n {\n if (this->_den == frac._den)\n {\n return Fraction(this->_num + frac._num, this->_den);\n }\n auto d = this->_den * frac._den;\n auto n = frac._den * this->_num + this->_den * frac._num;\n return Fraction(n, d);\n }\n\n /*!\n * @brief\n *\n * @param[in] frac\n * @return Fraction\n */\n constexpr auto operator-(const Fraction& frac) const -> Fraction\n {\n return *this + (-frac);\n }\n\n /*!\n * @brief\n *\n * @param[in] frac\n * @return Fraction\n */\n constexpr auto operator*(const Fraction& frac) const -> Fraction\n {\n auto n = this->_num * frac._num;\n auto d = this->_den * frac._den;\n return Fraction(std::move(n), std::move(d));\n }\n\n /*!\n * @brief\n *\n * @param[in] frac\n * @return Fraction\n */\n constexpr auto operator/(Fraction frac) const -> Fraction\n {\n frac.reciprocal();\n return *this * frac;\n }\n\n /*!\n * @brief\n *\n * @param[in] i\n * @return Fraction\n */\n constexpr auto operator+(const Z& i) const -> Fraction\n {\n auto n = this->_num + this->_den * i;\n return Fraction(std::move(n), this->_den);\n }\n\n /*!\n * @brief\n *\n * @param[in] i\n * @return Fraction\n */\n constexpr auto operator-(const Z& i) const -> Fraction\n {\n return *this + (-i);\n }\n\n // /*!\n // * @brief\n // *\n // * @param[in] i\n // * @return Fraction\n // */\n // constexpr Fraction operator*(const Z& i) const noexcept\n // {\n // auto n = _num * i;\n // return Fraction(n, _den);\n // }\n\n // /*!\n // * @brief\n // *\n // * @param[in] i\n // * @return Fraction\n // */\n // constexpr Fraction operator/(const Z& i) const noexcept\n // {\n // auto d = _den * i;\n // return Fraction(_num, d);\n // }\n\n /*!\n * @brief\n *\n * @param[in] frac\n * @return Fraction\n */\n constexpr auto operator+=(const Fraction& frac) -> Fraction&\n {\n return *this = *this + frac;\n }\n\n /*!\n * @brief\n *\n * @param[in] frac\n * @return Fraction\n */\n constexpr auto operator-=(const Fraction& frac) -> Fraction&\n {\n return *this = *this - frac;\n }\n\n /*!\n * @brief\n *\n * @param[in] frac\n * @return Fraction\n */\n constexpr auto operator*=(const Fraction& frac) -> Fraction&\n {\n return *this = *this * frac;\n }\n\n /*!\n * @brief\n *\n * @param[in] frac\n * @return Fraction\n */\n constexpr auto operator/=(const Fraction& frac) -> Fraction&\n {\n return *this = *this / frac;\n }\n\n /*!\n * @brief\n *\n * @param[in] i\n * @return Fraction\n */\n constexpr auto operator+=(const Z& i) -> Fraction&\n {\n return *this = *this + i;\n }\n\n /*!\n * @brief\n *\n * @param[in] i\n * @return Fraction\n */\n constexpr auto operator-=(const Z& i) -> Fraction&\n {\n return *this = *this - i;\n }\n\n /*!\n * @brief\n *\n * @param[in] i\n * @return Fraction\n */\n constexpr auto operator*=(const Z& i) -> Fraction&\n {\n const auto common = gcd(i, this->_den);\n if (common == Z(1))\n {\n this->_num *= i;\n }\n // else if (common == Z(0)) [[unlikely]] // both i and den are zero\n // {\n // this->_num = Z(0);\n // }\n else\n {\n this->_num *= (i / common);\n this->_den /= common;\n }\n return *this;\n }\n\n /*!\n * @brief\n *\n * @param[in] i\n * @return Fraction\n */\n constexpr auto operator/=(const Z& i) -> Fraction&\n {\n const auto common = gcd(this->_num, i);\n if (common == Z(1))\n {\n this->_den *= i;\n }\n // else if (common == Z(0)) [[unlikely]] // both i and num are zero\n // {\n // this->_den = Z(0);\n // }\n else\n {\n this->_den *= (i / common);\n this->_num /= common;\n }\n return *this;\n }\n\n /*!\n * @brief Three way comparison\n *\n * @param[in] frac\n * @return auto\n */\n template \n constexpr auto cmp(const Fraction& frac) const -> Fraction&\n {\n if (this->_den == frac._den)\n {\n return (this->_num - frac._num) * this->_den;\n }\n return this->_num * frac._den - this->_den * frac._num;\n }\n\n template \n constexpr auto operator==(const Fraction& rhs) const -> bool\n {\n if (this->_den == rhs._den)\n {\n return this->_num == rhs._num;\n }\n\n return this->_num * rhs._den == this->_den * rhs._num;\n }\n\n template \n constexpr auto operator<(const Fraction& rhs) const -> bool\n {\n if (this->_den == rhs._den)\n {\n return this->_num < rhs._num;\n }\n\n return this->_num * rhs._den < this->_den * rhs._num;\n }\n\n /**\n * @brief\n *\n */\n constexpr auto operator==(const Z& rhs) const -> bool\n {\n return this->_den == Z(1) && this->_num == rhs;\n }\n\n /**\n * @brief\n *\n */\n constexpr auto operator<(const Z& rhs) const -> bool\n {\n return this->_num < this->_den * rhs;\n }\n\n /**\n * @brief\n *\n */\n constexpr auto operator>(const Z& rhs) const -> bool\n {\n return this->_num > this->_den * rhs;\n }\n\n // /*!\n // * @brief\n // *\n // * @return double\n // */\n // constexpr explicit operator double())\n // {\n // return double(_num) / _den;\n // }\n\n // /**\n // * @brief\n // *\n // */\n // friend constexpr bool operator<(const Z& lhs, const Fraction& rhs))\n // {\n // return lhs * rhs.den() < rhs.num();\n // }\n};\n\n\n/*!\n * @brief\n *\n * @param[in] c\n * @param[in] frac\n * @return Fraction\n */\ntemplate \nconstexpr auto operator+(const Z& c, const Fraction& frac) -> Fraction\n{\n return frac + c;\n}\n\n/*!\n * @brief\n *\n * @param[in] c\n * @param[in] frac\n * @return Fraction\n */\ntemplate \nconstexpr auto operator-(const Z& c, const Fraction& frac) -> Fraction\n{\n return c + (-frac);\n}\n\n// /*!\n// * @brief\n// *\n// * @param[in] c\n// * @param[in] frac\n// * @return Fraction\n// */\n// template \n// constexpr Fraction operator*(const Z& c, const Fraction& frac)\n// {\n// return frac * c;\n// }\n\n/*!\n * @brief\n *\n * @param[in] c\n * @param[in] frac\n * @return Fraction\n */\ntemplate \nconstexpr auto operator+(int&& c, const Fraction& frac) -> Fraction\n{\n return frac + c;\n}\n\n/*!\n * @brief\n *\n * @param[in] c\n * @param[in] frac\n * @return Fraction\n */\ntemplate \nconstexpr auto operator-(int&& c, const Fraction& frac) -> Fraction\n{\n return (-frac) + c;\n}\n\n/*!\n * @brief\n *\n * @param[in] c\n * @param[in] frac\n * @return Fraction\n */\ntemplate \nconstexpr auto operator*(int&& c, const Fraction& frac) -> Fraction\n{\n return frac * c;\n}\n\n/*!\n * @brief\n *\n * @tparam _Stream\n * @tparam Z\n * @param[in] os\n * @param[in] frac\n * @return _Stream&\n */\ntemplate \nauto operator<<(_Stream& os, const Fraction& frac) -> _Stream&\n{\n os << frac.num() << \"/\" << frac.den();\n return os;\n}\n\n// For template deduction\n// Integral{Z} Fraction(const Z &, const Z &) noexcept -> Fraction;\n\n} // namespace fun\n", "meta": {"hexsha": "12bc01432b296e45c01722e9a343364263446aba", "size": 11568, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/include/pgcpp/fractions.hpp", "max_stars_repo_name": "luk036/pgcpp", "max_stars_repo_head_hexsha": "acef09303ebaa1334b5d30b727d975495e488d4f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-21T09:08:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T09:08:51.000Z", "max_issues_repo_path": "lib/include/pgcpp/fractions.hpp", "max_issues_repo_name": "luk036/pgcpp", "max_issues_repo_head_hexsha": "acef09303ebaa1334b5d30b727d975495e488d4f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-25T11:01:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-10T13:23:34.000Z", "max_forks_repo_path": "lib/include/pgcpp/fractions.hpp", "max_forks_repo_name": "luk036/pgcpp", "max_forks_repo_head_hexsha": "acef09303ebaa1334b5d30b727d975495e488d4f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-06-03T08:58:05.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-03T08:58:05.000Z", "avg_line_length": 18.5980707395, "max_line_length": 77, "alphanum_fraction": 0.4885892116, "num_tokens": 3247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.8354835289107307, "lm_q1q2_score": 0.7711840218530891}} {"text": "#include \n\n#include \n\n#include \"headers/euler.hpp\"\n\nconst int MIN_A_B = 1;\nconst int MAX_A_B = 100;\n\ntypedef boost::multiprecision::mpz_int big_int;\n\nint main(int argc, char** argv) {\n int largestA;\n int largestB;\n big_int largestDigitSum = 0;\n\n for (int a = MIN_A_B; a <= MAX_A_B; a++) {\n for (int b = MIN_A_B; b <= MAX_A_B; b++) {\n big_int n = euler::power(a, b);\n\n big_int digitSum = 0;\n\n while (n) {\n digitSum += n % 10;\n n /= 10;\n }\n\n if (digitSum > largestDigitSum) {\n largestDigitSum = digitSum;\n largestA = a;\n largestB = b;\n }\n }\n }\n\n std::cout << \"Largest digit sum of A^B is \" << largestDigitSum << \" \"\n << \"for A=\" << largestA << \", B=\" << largestB\n << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "edc162da892d975f6ac8e01e5be12b5678992dfe", "size": 839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "56.cpp", "max_stars_repo_name": "DouglasSherk/project-euler", "max_stars_repo_head_hexsha": "f3b188b199ff31671c6d7683b15675be7484c5b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "56.cpp", "max_issues_repo_name": "DouglasSherk/project-euler", "max_issues_repo_head_hexsha": "f3b188b199ff31671c6d7683b15675be7484c5b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "56.cpp", "max_forks_repo_name": "DouglasSherk/project-euler", "max_forks_repo_head_hexsha": "f3b188b199ff31671c6d7683b15675be7484c5b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.9761904762, "max_line_length": 71, "alphanum_fraction": 0.5518474374, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995733060719, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.7709682610817624}} {"text": "\n/*!\n * @file \n * @brief \n * @copyright alphya 2021\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef NYARUGA_UTIL_GROUP_HPP\n#define NYARUGA_UTIL_GROUP_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace nyaruga {\n\nnamespace util {\n\nnamespace detail {\n\ntemplate \nstruct SU1\n{\n using value_type = std::complex ;\nprivate:\n std::complex val_;\n constexpr SU1(const std::complex& v) noexcept : val_(v) {}\npublic:\n constexpr void set_val(const T& theta) noexcept { val_ = exp(std::complex{0,-1}*theta); }\n constexpr std::complex val(const T& theta) const noexcept { val_ = exp(std::complex{0,-1}*theta); return val_; }\n constexpr std::complex val() const noexcept{ return val_; }\n constexpr operator std::complex() const noexcept{ return val_; }\n constexpr SU1() noexcept = default;\n constexpr SU1(const SU1& v) noexcept : val_(v.val_) {}\n constexpr SU1(const T& theta) noexcept : val_(exp(std::complex{0,-1}*theta)) {}\n friend SU1 operator*(const SU1& lhs, const SU1 & rhs) noexcept { return SU1(lhs.val()*rhs.val()); }\n constexpr SU1 conj() { return std::conj(val_); }\n};\n\ntemplate \nstruct SO2\n{\n using value_type = Eigen::Matrix ;\nprivate:\n Eigen::Matrix val_;\n constexpr SO2(const Eigen::Matrix& v) noexcept : val_(v) {}\npublic:\n constexpr void set_val(const T& theta) noexcept { val_ << cos(theta), -sin(theta), sin(theta), cos(theta); }\n constexpr Eigen::Matrix val(const T& theta) const noexcept { val_ << cos(theta), -sin(theta), sin(theta), cos(theta); return val_; };\n constexpr Eigen::Matrix val() const noexcept{ return val_; };\n constexpr operator Eigen::Matrix() const noexcept { return val_; }\n constexpr SO2() noexcept = default;\n constexpr SO2(const SO2& v) noexcept : val_(v.val_) {}\n constexpr SO2(const T& theta) noexcept { val_ << cos(theta), -sin(theta), sin(theta), cos(theta);}\n friend SO2 operator*(const SO2& lhs, const SO2 & rhs) noexcept { return SO2(lhs.val()*rhs.val()); }\n constexpr SO2 transpose() { return SO2(val_.transpose()); }\n};\n\ntemplate \nstruct SO3 // http://www.tuhep.phys.tohoku.ac.jp/~watamura/kougi/GP2012_4.pdf\n{\n using value_type = Eigen::Matrix ;\nprivate:\n Eigen::Matrix val_;\n constexpr SO3(const Eigen::Matrix& v) noexcept : val_(v) {}\n\n // alpha, beta, gamma はオイラー角\n constexpr value_type calc_val(const T& alpha, const T& beta, const T& gamma) noexcept\n {\n value_type RX, RY, RZ;\n RX << 1, 0, 0, 0, cos(alpha), -sin(alpha), 0, sin(alpha), cos(alpha);\n RY << cos(beta), 0, sin(beta), 0, 1, 0, -sin(beta), 0, cos(beta);\n RZ << cos(gamma), -sin(gamma), 0, sin(gamma), cos(gamma), 0, 0, 0, 1;\n return RX*(RY*RZ);\n }\n\npublic:\n // alpha, beta, gamma はオイラー角\n constexpr void set_val(const T& alpha, const T& beta, const T& gamma) noexcept { val_ = calc_val(alpha, beta, gamma); }\n constexpr value_type val(const T& alpha, const T& beta, const T& gamma) const noexcept { val_ = calc_val(alpha, beta, gamma); return val_; };\n constexpr value_type val() const noexcept{ return val_; };\n constexpr operator value_type() const noexcept { return val_; }\n constexpr SO3() noexcept = default;\n constexpr SO3(const SO3& v) noexcept : val_(v.val_) {}\n constexpr SO3(const T& alpha, const T& beta, const T& gamma) noexcept : val_(calc_val(alpha, beta, gamma)) {}\n friend SO3 operator*(const SO3& lhs, const SO3 & rhs) noexcept { return SO3(lhs.val()*rhs.val()); }\n constexpr SO3 transpose() { return SO3(val_.transpose()); }\n};\n\n} // detail\n\nusing detail::SU1;\nusing detail::SO2;\nusing detail::SO3;\n\n} // util\n\n} // nyaruga\n\n/* how to use\n\n# include \"group.hpp\"\n\nusing namespace nyaruga::util;\nusing namespace std::numbers;\n\nint main(){\n SU1 a(pi/2*23);\n SU1 b(pi/32);\n std::cout << norm((a*b).val()) << \"\\n\"; // 1\n std::cout << (a.conj()*(a)).val() << \"\\n\\n\"; // E\n \n SO2 c(pi/2+2);\n SO2 d(pi/2*24+4);\n std::cout << (c*d).val() << \"\\n\";\n std::cout << (c*c.transpose()).val() << \"\\n\"; // E\n std::cout << (c*d).val().determinant() << \"\\n\\n\"; //1\n\n SO3 e(pi/2+2, 23., 4.);\n SO3 f(pi/2*24+4, 3., 42.);\n std::cout << (e*f).val() << \"\\n\";\n std::cout << (e*e.transpose()).val() << \"\\n\"; // E\n std::cout << (e*f).val().determinant() << \"\\n\"; //1\n}\n\n*/\n\n\n#endif // #ifndef NYARUGA_UTIL_GROUP_HPP", "meta": {"hexsha": "87b42f3fd3550dd6e8c17f6a05ae1f8d6ee2172e", "size": 4713, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nyaruga_util/group.hpp", "max_stars_repo_name": "alphya/nyaruga_util", "max_stars_repo_head_hexsha": "a75d388b2fe80100760f9b5fc7e959e4846b590f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nyaruga_util/group.hpp", "max_issues_repo_name": "alphya/nyaruga_util", "max_issues_repo_head_hexsha": "a75d388b2fe80100760f9b5fc7e959e4846b590f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nyaruga_util/group.hpp", "max_forks_repo_name": "alphya/nyaruga_util", "max_forks_repo_head_hexsha": "a75d388b2fe80100760f9b5fc7e959e4846b590f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.171641791, "max_line_length": 145, "alphanum_fraction": 0.6314449395, "num_tokens": 1428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947101574298, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.77039038362288}} {"text": "// C++ includes\n#include \nusing namespace std;\n\n// Eigen includes\n#include \nusing namespace Eigen;\n\n// autodiff include\n#include \n#include \nusing namespace autodiff;\n\n// The vector function with parameters for which the Jacobian is needed\nVectorXdual f(const VectorXdual& x, dual p)\n{\n return x * exp(p);\n}\n\nint main()\n{\n VectorXdual x(5); // the input vector x with 5 variables\n x << 1, 2, 3, 4, 5; // x = [1, 2, 3, 4, 5]\n\n dual p = 3; // the input parameter vector p with 3 variables\n\n VectorXdual F; // the output vector F = f(x, p) evaluated together with Jacobian below\n\n MatrixXd Jpx = jacobian(f, wrtpack(p, x), at(x, p), F); // evaluate the function and the Jacobian matrix [dF/dp, dF/dx]\n\n cout << \"F = \\n\" << F << endl; // print the evaluated output vector F\n cout << \"Jpx = \\n\" << Jpx << endl; // print the evaluated Jacobian matrix [dF/dp, dF/dx]\n}\n", "meta": {"hexsha": "5863836ee9626684a0c3ccee4ba87fd605436df4", "size": 970, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/forward/example-forward-jacobian-derivatives-using-eigen-with-scalar.cpp", "max_stars_repo_name": "rbharvs/autodiff", "max_stars_repo_head_hexsha": "d0305026b84c2f85f74012f312cc57bb1a894bd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-21T04:02:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T04:02:38.000Z", "max_issues_repo_path": "examples/forward/example-forward-jacobian-derivatives-using-eigen-with-scalar.cpp", "max_issues_repo_name": "gayatri-a-b/autodiff", "max_issues_repo_head_hexsha": "98bdfea087cb67dd6e2a1a399e90bbd7ac4eb326", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-22T07:15:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-22T07:15:49.000Z", "max_forks_repo_path": "examples/forward/example-forward-jacobian-derivatives-using-eigen-with-scalar.cpp", "max_forks_repo_name": "gayatri-a-b/autodiff", "max_forks_repo_head_hexsha": "98bdfea087cb67dd6e2a1a399e90bbd7ac4eb326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-02-26T13:14:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T03:52:45.000Z", "avg_line_length": 28.5294117647, "max_line_length": 124, "alphanum_fraction": 0.6494845361, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750400464604, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7703103119690538}} {"text": "#include \"register.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\nvoid closest_rotation(\n\tconst Eigen::Matrix3d & M,\n\tEigen::Matrix3d & R)\n{\n\n\t// My code\n\tEigen::JacobiSVD svd(M, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\tEigen::Matrix3d U = svd.matrixU();\n\tEigen::Matrix3d V = svd.matrixV();\n\tEigen::Matrix3d Omega = Eigen::Matrix3d::Identity();\n\tOmega(2, 2) = (U*V.transpose()).determinant();\n\tR = (U * Omega * V.transpose()).transpose();\n}\n\n\nvoid point_triangle_distance(\n\tconst Eigen::RowVector3d & x,\n\tconst Eigen::RowVector3d & aa,\n\tconst Eigen::RowVector3d & bb,\n\tconst Eigen::RowVector3d & cc,\n\tdouble & dd,\n\tEigen::RowVector3d & p)\n{\n\n\tEigen::RowVector3d B = aa;\n\tEigen::RowVector3d E0 = bb - aa;\n\tEigen::RowVector3d E1 = cc - aa;\n\tEigen::RowVector3d P = x;\n\n\tdouble a = E0.dot(E0);\n\tdouble b = E0.dot(E1);\n\tdouble c = E1.dot(E1);\n\tdouble d = E0.dot(B - P);\n\tdouble e = E1.dot(B - P);\n\tdouble f = (B - P).dot(B - P);\n\n\tdouble s = b * e - c * d;\n\tdouble t = b * d - a * e;\n\tdouble det = a * c - b * b;\n\n\tif (s + t <= det) {\n\t\tif (s < 0) {\n\t\t\tif (t < 0) {\n\t\t\t\t// ===============\n\t\t\t\t// region 4\n\t\t\t\tif (d < 0) {\n\t\t\t\t\tt = 0;\n\t\t\t\t\tif (-d >= a)\n\t\t\t\t\t\ts = 1;\n\t\t\t\t\telse\n\t\t\t\t\t\ts = -d / a;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ts = 0;\n\t\t\t\t\tif (e >= 0)\n\t\t\t\t\t\tt = 0;\n\t\t\t\t\telse if (-e >= c)\n\t\t\t\t\t\tt = 1;\n\t\t\t\t\telse\n\t\t\t\t\t\tt = -e / c;\n\t\t\t\t}\n\t\t\t\t// ===============\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// ===============\n\t\t\t\t// region 3\n\t\t\t\ts = 0;\n\t\t\t\tif (e >= 0)\n\t\t\t\t\tt = 0;\n\t\t\t\telse if (-e >= c)\n\t\t\t\t\tt = 1;\n\t\t\t\telse\n\t\t\t\t\tt = -e / c;\n\t\t\t\t// ===============\n\t\t\t}\n\t\t}\n\t\telse if (t < 0) {\n\t\t\t// ===============\n\t\t\t// region 5\n\t\t\tt = 0;\n\t\t\tif (d >= 0)\n\t\t\t\ts = 0;\n\t\t\telse if (-d >= a)\n\t\t\t\ts = 1;\n\t\t\telse\n\t\t\t\ts = -d / a;\n\t\t\t// ===============\n\t\t}\n\t\telse {\n\t\t\t// ===============\n\t\t\t// region 0\n\t\t\ts /= det;\n\t\t\tt /= det;\n\t\t\t// ===============\n\t\t}\n\t}\n\telse {\n\t\tif (s < 0) {\n\t\t\t// ===============\n\t\t\t// region 2\n\t\t\tdouble temp0 = b + d;\n\t\t\tdouble temp1 = c + e;\n\t\t\tif (temp1 > temp0) {\n\t\t\t\tdouble num = temp1 - temp0;\n\t\t\t\tdouble denom = a - 2 * b + c;\n\t\t\t\tif (num >= denom)\n\t\t\t\t\ts = 1;\n\t\t\t\telse\n\t\t\t\t\ts = num / denom;\n\t\t\t\tt = 1 - s;\n\t\t\t}\n\t\t\telse {\n\t\t\t\ts = 0;\n\t\t\t\tif (temp1 <= 0)\n\t\t\t\t\tt = 1;\n\t\t\t\telse if (e >= 0)\n\t\t\t\t\tt = 0;\n\t\t\t\telse\n\t\t\t\t\tt = -e / c;\n\t\t\t}\n\t\t\t// ===============\n\t\t}\n\t\telse if (t < 0) {\n\t\t\t// ===============\n\t\t\t// region 6\n\t\t\tdouble temp0 = b + e;\n\t\t\tdouble temp1 = a + d;\n\t\t\tif (temp1 > temp0) {\n\t\t\t\tdouble num = temp1 - temp0;\n\t\t\t\tdouble denom = a - 2 * b + c;\n\t\t\t\tif (num >= denom)\n\t\t\t\t\tt = 1;\n\t\t\t\telse\n\t\t\t\t\tt = num / denom;\n\t\t\t\ts = 1 - t;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tt = 0;\n\t\t\t\tif (temp1 <= 0)\n\t\t\t\t\ts = 1;\n\t\t\t\telse if (d >= 0)\n\t\t\t\t\ts = 0;\n\t\t\t\telse\n\t\t\t\t\ts = -d / a;\n\t\t\t}\n\t\t\t// ===============\n\t\t}\n\t\telse {\n\t\t\t// ===============\n\t\t\t// region 1\n\t\t\tdouble num = (c + e) - (b + d);\n\t\t\tif (num <= 0)\n\t\t\t\ts = 0;\n\t\t\telse {\n\t\t\t\tdouble denom = a - 2 * b + c;\n\t\t\t\tif (num >= denom)\n\t\t\t\t\ts = 1;\n\t\t\t\telse\n\t\t\t\t\ts = num / denom;\n\t\t\t}\n\t\t\tt = 1 - s;\n\t\t\t// ===============\n\t\t}\n\t}\n\tp = B + s * E0 + t * E1;\n\tdd = (p - x).norm();\n}\n\n\n\n\n\nvoid point_to_plane_rigid_matching(\n\tconst Eigen::MatrixXd & X,\n\tconst Eigen::MatrixXd & P,\n\tconst Eigen::MatrixXd & N,\n\tEigen::Matrix3d & R,\n\tEigen::RowVector3d & t)\n{\n\tR = Eigen::Matrix3d::Identity();\n\tt = Eigen::RowVector3d::Zero();\n\n\tint k = X.rows();\n\t// construct b\n\tEigen::VectorXd RHS, u;\n\tEigen::MatrixXd LHS;\n\tRHS.resize(k);\n\tLHS.resize(k, 6);\n\tu.resize(6);\n\tfor (int ii = 0; ii < k; ii++) {\n\t\t// assemble RHS\n\t\tRHS(ii) = N(ii, 0)*(P(ii, 0) - X(ii, 0)) +\n\t\t\tN(ii, 1)*(P(ii, 1) - X(ii, 1)) +\n\t\t\tN(ii, 2)*(P(ii, 2) - X(ii, 2));\n\t\t// assemble A\n\t\tLHS.row(ii) << N(ii, 2)*X(ii, 1) - N(ii, 1)*X(ii, 2),\n\t\t\tN(ii, 0)*X(ii, 2) - N(ii, 2)*X(ii, 0),\n\t\t\tN(ii, 1)*X(ii, 0) - N(ii, 0)*X(ii, 1),\n\t\t\tN(ii, 0),\n\t\t\tN(ii, 1),\n\t\t\tN(ii, 2);\n\t}\n\tu = LHS.colPivHouseholderQr().solve(RHS);\n\tEigen::Matrix3d M;\n\tM << 1, -u(2), u(1),\n\t\tu(2), 1, -u(0),\n\t\t-u(1), u(0), 1;\n\tclosest_rotation(M, R);\n\tt(0) = u(3);\n\tt(1) = u(4);\n\tt(2) = u(5);\n}\n\nvoid point_mesh_distance(\n\tconst Eigen::MatrixXd & X,\n\tconst Eigen::MatrixXd & VY,\n\tconst Eigen::MatrixXi & FY,\n\tEigen::VectorXd & D,\n\tEigen::MatrixXd & P,\n\tEigen::MatrixXd & N)\n{\n\t// compute face normals\n\tEigen::MatrixXd FN;\n\tigl::per_face_normals(VY, FY, Eigen::Vector3d(1, 1, 1).normalized(), FN);\n\n\tD.resize(X.rows());\n\tP.resize(X.rows(), 3);\n\tN.resize(X.rows(), 3);\n\n\tEigen::RowVector3d Xpt, a, b, c, p;\n\tdouble dist;\n\tdouble minDist;\n\tint minIdx;\n\tdouble pmin_x, pmin_y, pmin_z;\n\tfor (int ii = 0; ii < X.rows(); ii++) { // loop over points X\n\t\tminDist = std::numeric_limits::max();\n\n\t\tfor (int jj = 0; jj < FY.rows(); jj++) { // loop over triangles\n\t\t\tXpt = X.row(ii);\n\t\t\ta = VY.row(FY(jj, 0));\n\t\t\tb = VY.row(FY(jj, 1));\n\t\t\tc = VY.row(FY(jj, 2));\n\t\t\tpoint_triangle_distance(Xpt, a, b, c, dist, p);\n\n\t\t\tif (dist < minDist) {\n\t\t\t\tminDist = dist;\n\t\t\t\tminIdx = jj;\n\t\t\t\tpmin_x = p(0);\n\t\t\t\tpmin_y = p(1);\n\t\t\t\tpmin_z = p(2);\n\t\t\t}\n\t\t}\n\t\tD(ii) = minDist;\n\t\tP.row(ii) << pmin_x, pmin_y, pmin_z;\n\t\tN.row(ii) = FN.row(minIdx);\n\t}\n}\n\ndouble icp_single_iteration(\n\tconst Eigen::MatrixXd & VX,\n\tconst Eigen::MatrixXi & FX,\n\tconst Eigen::MatrixXd & VY,\n\tconst Eigen::MatrixXi & FY,\n\tconst int num_samples,\n\tEigen::Matrix3d & R,\n\tEigen::RowVector3d & t)\n{\n\tR = Eigen::Matrix3d::Identity();\n\tt = Eigen::RowVector3d::Zero();\n\n\tEigen::MatrixXd X, P, N;\n\tEigen::VectorXd D;\n\n\trandom_points_on_mesh(num_samples, VX, FX, X);\n\n\tpoint_mesh_distance(X, VY, FY, D, P, N);\n\n\t// point-to-plane\n\tpoint_to_plane_rigid_matching(X, P, N, R, t);\n\n\treturn D.sum()/D.rows();\n}", "meta": {"hexsha": "d5faaa1dc98d384c8e2f558b3134b9c1ad64c024", "size": 5616, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/register.cpp", "max_stars_repo_name": "rozentill/Front2Back", "max_stars_repo_head_hexsha": "c14e77d3cea923026129de9f04f32327d6ee4381", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-04-01T12:48:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T07:43:27.000Z", "max_issues_repo_path": "src/register.cpp", "max_issues_repo_name": "rozentill/Front2Back", "max_issues_repo_head_hexsha": "c14e77d3cea923026129de9f04f32327d6ee4381", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/register.cpp", "max_forks_repo_name": "rozentill/Front2Back", "max_forks_repo_head_hexsha": "c14e77d3cea923026129de9f04f32327d6ee4381", "max_forks_repo_licenses": ["Apache-2.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.2328767123, "max_line_length": 85, "alphanum_fraction": 0.4926994302, "num_tokens": 2113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.7702902093073563}} {"text": "#include \n\nint main() {\n\n\n // To generate the (symmetric positive-definite) matrix:\n\n // const size_t dim = 5;\n // arma::mat S(dim, dim, arma::fill::randu);\n // S = 0.5 * (S + S.t());\n // S += dim * arma::eye(arma::size(S));\n // S.save(\"S.dat\", arma::arma_ascii);\n\n // To load the pre-generated matrix:\n\n arma::mat S;\n S.load(\"S.dat\");\n\n S.print(\"S\");\n\n // arma::vec Lam_S_vec(dim);\n // arma::mat Lam_S_mat(dim, dim);\n // arma::mat L_S(dim, dim);\n arma::vec Lam_S_vec;\n arma::mat Lam_S_mat;\n arma::mat L_S;\n\n arma::eig_sym(Lam_S_vec, L_S, S);\n // What's wrong with this?\n // Lam_S_mat = Lam_S_vec * arma::eye(Lam_S_vec.n_elem, Lam_S_vec.n_elem);\n Lam_S_mat = arma::diagmat(Lam_S_vec);\n arma::mat Lam_sqrt_inv = arma::sqrt(arma::inv(Lam_S_mat));\n arma::mat symm_orthog = L_S * Lam_sqrt_inv * L_S.t();\n\n L_S.print(\"L_S\");\n Lam_S_vec.print(\"Lam_S_vec\");\n Lam_S_mat.print(\"Lam_S_mat\");\n Lam_sqrt_inv.print(\"Lam_sqrt_inv\");\n symm_orthog.print(\"symm_orthog\");\n\n // Demonstration that matrix operations require diagonalization,\n // operation on the eigenvalues, then back-transformation to the\n // original basis.\n arma::mat S_inv = arma::inv(S);\n arma::mat Lam_inv = arma::inv(Lam_S_mat);\n arma::mat S_inv_2 = L_S * Lam_inv * L_S.t();\n arma::mat S_pinv = arma::pinv(S);\n arma::mat S_inv_sympd = arma::inv_sympd(S);\n\n S_inv.print(\"S_inv\");\n S_inv_2.print(\"S_inv_2\");\n S_pinv.print(\"S_pinv\");\n S_inv_sympd.print(\"S_inv_sympd\");\n\n return 0;\n\n}\n", "meta": {"hexsha": "d2985fc70b9387b95c95cb5717b4dca7452a20c6", "size": 1577, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/armadillo/inv_sqrt.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/inv_sqrt.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/inv_sqrt.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": 27.1896551724, "max_line_length": 88, "alphanum_fraction": 0.6157260621, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455085, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7702505228787124}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n#define N 100000\n\nusing namespace boost::random;\nusing namespace boost::multiprecision;\n\n\ncpp_bin_float_50 random_gen(){\n\tboost::random::random_device seeder;\n\tboost::random::mt19937 gen(seeder());\n\n\tcpp_bin_float_50 rand_num = generate_canonical::digits>(gen);\n\treturn rand_num;\n}\n\nvoid seq_monte_carlo(){\n\tint count;\n\tint i;\n\t//int n = vm[\"n\"].as();\n\tint n = N;\n\n\tcpp_bin_float_50 pi;\n\tcpp_bin_float_50 x,y;\n\tcpp_bin_float_50 PI = boost::math::constants::pi();\n\n\tcount = 0;\n\tfor(i = 0; i < n; i++){\n\t\tx = random_gen();\n\t\ty = random_gen();\n\t\tfor(int j =0;j<1000;j++){}\n\t\tif(x*x + y*y <= 1.0){\n\t\t\tcount++;\n\t\t}\n\t}\n\tpi = 4.0 * (double) count / (double) n;\n\t\n\tcpp_bin_float_50 error = (pi - PI) / PI;\n\n\tstd::cout << std::setprecision(20); \n\tstd::cout << pi << std::endl;\n\tstd::cout << PI << std::endl;\n\tstd::cout << error << std::endl;\n\n\n}\n\nvoid par_monte_carlo(){\n\tint count_private[N] = {0};\n\tint count = 0;\n\tint i;\n\t//int n = vm[\"n\"].as();\n\tint n = N;\n\tint chunk_size = 1000;\n\n\tcpp_bin_float_50 pi;\n\tcpp_bin_float_50 x,y;\n\tcpp_bin_float_50 PI = boost::math::constants::pi();\n\n\t#pragma omp parallel \\\n\t shared(count_private, chunk_size) private(i,x,y) \n\t{\n #pragma omp for schedule(dynamic,chunk_size) nowait\n\t\tfor(i = 0; i < n; i++){\n\t\t\tx = random_gen();\n\t\t\ty = random_gen();\n\t\t\tif(x*x + y*y <= 1.0){\n\t\t\t\tcount_private[i]++;\n\t\t\t}\n\t\t}\n\t}\n\t#pragma omp parallel for reduction(+:count)\n\tfor(i = 0; i < n; i++){\n\t\tcount += count_private[i];\n\t}\n\tpi = 4.0 * (double) count / (double) n;\n\t\n\tcpp_bin_float_50 error = (pi - PI) / PI;\n\n\tstd::cout << std::setprecision(20); \n\tstd::cout << pi << std::endl;\n\tstd::cout << PI << std::endl;\n\tstd::cout << error << std::endl;\n}\n\n\nlong time_cal(void (*func)()){\n\t//clock_t begin = clock();\n//\tstd::time_t start, end;\n//\tlong delta = 0;\n//\tstart = std::time(NULL);\n\t\n\tstruct timespec start,end;\n\n\tclock_gettime(CLOCK_REALTIME, &start);\n\t(*func)();\n\tclock_gettime(CLOCK_REALTIME, &end);\n\tlong delta = end.tv_sec - start.tv_sec;\n\t\n\tstd::cout << start.tv_sec << \" \" << start.tv_nsec << std::endl;\n\tstd::cout << end.tv_sec << \" \" << end.tv_nsec << std::endl;\n\treturn delta;\n}\n\n\nint main(int argc, char *argv[]){\n\n//\toptions_description desc{\"Options\"};\n//\tdesc.add_options()\n//\t\t(\"help,h\", \"Help screen\")\n// \t\t(\"n\", value()->default_value(10000), \"Number of random counts\")\n//\t;\n//\tvariables_map vm;\n//\tstore(parse_command_line(argc, argv, desc), vm);\n//\tnotify(vm);\n//\n//\tstd::random_device seeder;\n//\tboost::random::mt19937 gen(seeder());\n\n\tauto seq_time = time_cal(seq_monte_carlo);\n\tauto par_time = time_cal(par_monte_carlo);\n\tstd::cout << seq_time << std::endl;\n\tstd::cout << par_time << std::endl;\n}\n", "meta": {"hexsha": "47d23a6321643c1e1efbcc7d2939d1f42f5f5657", "size": 2968, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homework2/hw2_1.cc", "max_stars_repo_name": "ONLY-VEDA/MPI_2019_SPRING", "max_stars_repo_head_hexsha": "b0a8bd58dfbc62613b54b99b8e85a74f77a2c468", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homework2/hw2_1.cc", "max_issues_repo_name": "ONLY-VEDA/MPI_2019_SPRING", "max_issues_repo_head_hexsha": "b0a8bd58dfbc62613b54b99b8e85a74f77a2c468", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework2/hw2_1.cc", "max_forks_repo_name": "ONLY-VEDA/MPI_2019_SPRING", "max_forks_repo_head_hexsha": "b0a8bd58dfbc62613b54b99b8e85a74f77a2c468", "max_forks_repo_licenses": ["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.8307692308, "max_line_length": 118, "alphanum_fraction": 0.6391509434, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7701870887460357}} {"text": "// negative_binomial_example1.cpp\r\n\r\n// Copyright Paul A. Bristow 2007, 2010.\r\n\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// Example 1 of using negative_binomial distribution.\r\n\r\n//[negative_binomial_eg1_1\r\n\r\n/*`\r\nBased on [@http://en.wikipedia.org/wiki/Negative_binomial_distribution\r\na problem by Dr. Diane Evans,\r\nProfessor of Mathematics at Rose-Hulman Institute of Technology].\r\n\r\nPat is required to sell candy bars to raise money for the 6th grade field trip.\r\nThere are thirty houses in the neighborhood,\r\nand Pat is not supposed to return home until five candy bars have been sold.\r\nSo the child goes door to door, selling candy bars.\r\nAt each house, there is a 0.4 probability (40%) of selling one candy bar\r\nand a 0.6 probability (60%) of selling nothing.\r\n\r\nWhat is the probability mass (density) function (pdf) for selling the last (fifth)\r\ncandy bar at the nth house?\r\n\r\nThe Negative Binomial(r, p) distribution describes the probability of k failures\r\nand r successes in k+r Bernoulli(p) trials with success on the last trial.\r\n(A [@http://en.wikipedia.org/wiki/Bernoulli_distribution Bernoulli trial]\r\nis one with only two possible outcomes, success of failure,\r\nand p is the probability of success).\r\nSee also [@ http://en.wikipedia.org/wiki/Bernoulli_distribution Bernoulli distribution]\r\nand [@http://www.math.uah.edu/stat/bernoulli/Introduction.xhtml Bernoulli applications].\r\n\r\nIn this example, we will deliberately produce a variety of calculations\r\nand outputs to demonstrate the ways that the negative binomial distribution\r\ncan be implemented with this library: it is also deliberately over-commented.\r\n\r\nFirst we need to #define macros to control the error and discrete handling policies.\r\nFor this simple example, we want to avoid throwing\r\nan exception (the default policy) and just return infinity.\r\nWe want to treat the distribution as if it was continuous,\r\nso we choose a discrete_quantile policy of real,\r\nrather than the default policy integer_round_outwards.\r\n*/\r\n#define BOOST_MATH_OVERFLOW_ERROR_POLICY ignore_error\r\n#define BOOST_MATH_DISCRETE_QUANTILE_POLICY real\r\n/*`\r\nAfter that we need some includes to provide easy access to the negative binomial distribution,\r\n[caution It is vital to #include distributions etc *after* the above #defines]\r\nand we need some std library iostream, of course.\r\n*/\r\n#include \r\n // for negative_binomial_distribution\r\n using boost::math::negative_binomial; // typedef provides default type is double.\r\n using ::boost::math::pdf; // Probability mass function.\r\n using ::boost::math::cdf; // Cumulative density function.\r\n using ::boost::math::quantile;\r\n\r\n#include \r\n using std::cout; using std::endl;\r\n using std::noshowpoint; using std::fixed; using std::right; using std::left;\r\n#include \r\n using std::setprecision; using std::setw;\r\n\r\n#include \r\n using std::numeric_limits;\r\n//] [negative_binomial_eg1_1]\r\n\r\nint main()\r\n{\r\n cout <<\"Selling candy bars - using the negative binomial distribution.\"\r\n << \"\\nby Dr. Diane Evans,\"\r\n \"\\nProfessor of Mathematics at Rose-Hulman Institute of Technology,\"\r\n << \"\\nsee http://en.wikipedia.org/wiki/Negative_binomial_distribution\\n\"\r\n << endl;\r\n cout << endl;\r\n cout.precision(5);\r\n // None of the values calculated have a useful accuracy as great this, but\r\n // INF shows wrongly with < 5 !\r\n // https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=240227\r\n//[negative_binomial_eg1_2\r\n/*`\r\nIt is always sensible to use try and catch blocks because defaults policies are to\r\nthrow an exception if anything goes wrong.\r\n\r\nA simple catch block (see below) will ensure that you get a\r\nhelpful error message instead of an abrupt program abort.\r\n*/\r\n try\r\n {\r\n/*`\r\nSelling five candy bars means getting five successes, so successes r = 5.\r\nThe total number of trials (n, in this case, houses visited) this takes is therefore\r\n = sucesses + failures or k + r = k + 5.\r\n*/\r\n double sales_quota = 5; // Pat's sales quota - successes (r).\r\n/*`\r\nAt each house, there is a 0.4 probability (40%) of selling one candy bar\r\nand a 0.6 probability (60%) of selling nothing.\r\n*/\r\n double success_fraction = 0.4; // success_fraction (p) - so failure_fraction is 0.6.\r\n/*`\r\nThe Negative Binomial(r, p) distribution describes the probability of k failures\r\nand r successes in k+r Bernoulli(p) trials with success on the last trial.\r\n(A [@http://en.wikipedia.org/wiki/Bernoulli_distribution Bernoulli trial]\r\nis one with only two possible outcomes, success of failure,\r\nand p is the probability of success).\r\n\r\nWe therefore start by constructing a negative binomial distribution\r\nwith parameters sales_quota (required successes) and probability of success.\r\n*/\r\n negative_binomial nb(sales_quota, success_fraction); // type double by default.\r\n/*`\r\nTo confirm, display the success_fraction & successes parameters of the distribution.\r\n*/\r\n cout << \"Pat has a sales per house success rate of \" << success_fraction\r\n << \".\\nTherefore he would, on average, sell \" << nb.success_fraction() * 100\r\n << \" bars after trying 100 houses.\" << endl;\r\n\r\n int all_houses = 30; // The number of houses on the estate.\r\n\r\n cout << \"With a success rate of \" << nb.success_fraction()\r\n << \", he might expect, on average,\\n\"\r\n \"to need to visit about \" << success_fraction * all_houses\r\n << \" houses in order to sell all \" << nb.successes() << \" bars. \" << endl;\r\n/*`\r\n[pre\r\nPat has a sales per house success rate of 0.4.\r\nTherefore he would, on average, sell 40 bars after trying 100 houses.\r\nWith a success rate of 0.4, he might expect, on average,\r\nto need to visit about 12 houses in order to sell all 5 bars.\r\n]\r\n\r\nThe random variable of interest is the number of houses\r\nthat must be visited to sell five candy bars,\r\nso we substitute k = n - 5 into a negative_binomial(5, 0.4)\r\nand obtain the __pdf of the distribution of houses visited.\r\nObviously, the best possible case is that Pat makes sales on all the first five houses.\r\n\r\nWe calculate this using the pdf function:\r\n*/\r\n cout << \"Probability that Pat finishes on the \" << sales_quota << \"th house is \"\r\n << pdf(nb, 5 - sales_quota) << endl; // == pdf(nb, 0)\r\n/*`\r\nOf course, he could not finish on fewer than 5 houses because he must sell 5 candy bars.\r\nSo the 5th house is the first that he could possibly finish on.\r\n\r\nTo finish on or before the 8th house, Pat must finish at the 5th, 6th, 7th or 8th house.\r\nThe probability that he will finish on *exactly* ( == ) on any house\r\nis the Probability Density Function (pdf).\r\n*/\r\n cout << \"Probability that Pat finishes on the 6th house is \"\r\n << pdf(nb, 6 - sales_quota) << endl;\r\n cout << \"Probability that Pat finishes on the 7th house is \"\r\n << pdf(nb, 7 - sales_quota) << endl;\r\n cout << \"Probability that Pat finishes on the 8th house is \"\r\n << pdf(nb, 8 - sales_quota) << endl;\r\n/*`\r\n[pre\r\nProbability that Pat finishes on the 6th house is 0.03072\r\nProbability that Pat finishes on the 7th house is 0.055296\r\nProbability that Pat finishes on the 8th house is 0.077414\r\n]\r\n\r\nThe sum of the probabilities for these houses is the Cumulative Distribution Function (cdf).\r\nWe can calculate it by adding the individual probabilities.\r\n*/\r\n cout << \"Probability that Pat finishes on or before the 8th house is sum \"\r\n \"\\n\" << \"pdf(sales_quota) + pdf(6) + pdf(7) + pdf(8) = \"\r\n // Sum each of the mass/density probabilities for houses sales_quota = 5, 6, 7, & 8.\r\n << pdf(nb, 5 - sales_quota) // 0 failures.\r\n + pdf(nb, 6 - sales_quota) // 1 failure.\r\n + pdf(nb, 7 - sales_quota) // 2 failures.\r\n + pdf(nb, 8 - sales_quota) // 3 failures.\r\n << endl;\r\n/*`[pre\r\npdf(sales_quota) + pdf(6) + pdf(7) + pdf(8) = 0.17367\r\n]\r\n\r\nOr, usually better, by using the negative binomial *cumulative* distribution function.\r\n*/\r\n cout << \"\\nProbability of selling his quota of \" << sales_quota\r\n << \" bars\\non or before the \" << 8 << \"th house is \"\r\n << cdf(nb, 8 - sales_quota) << endl;\r\n/*`[pre\r\nProbability of selling his quota of 5 bars on or before the 8th house is 0.17367\r\n]*/\r\n cout << \"\\nProbability that Pat finishes exactly on the 10th house is \"\r\n << pdf(nb, 10 - sales_quota) << endl;\r\n cout << \"\\nProbability of selling his quota of \" << sales_quota\r\n << \" bars\\non or before the \" << 10 << \"th house is \"\r\n << cdf(nb, 10 - sales_quota) << endl;\r\n/*`\r\n[pre\r\nProbability that Pat finishes exactly on the 10th house is 0.10033\r\nProbability of selling his quota of 5 bars on or before the 10th house is 0.3669\r\n]*/\r\n cout << \"Probability that Pat finishes exactly on the 11th house is \"\r\n << pdf(nb, 11 - sales_quota) << endl;\r\n cout << \"\\nProbability of selling his quota of \" << sales_quota\r\n << \" bars\\non or before the \" << 11 << \"th house is \"\r\n << cdf(nb, 11 - sales_quota) << endl;\r\n/*`[pre\r\nProbability that Pat finishes on the 11th house is 0.10033\r\nProbability of selling his quota of 5 candy bars\r\non or before the 11th house is 0.46723\r\n]*/\r\n cout << \"Probability that Pat finishes exactly on the 12th house is \"\r\n << pdf(nb, 12 - sales_quota) << endl;\r\n\r\n cout << \"\\nProbability of selling his quota of \" << sales_quota\r\n << \" bars\\non or before the \" << 12 << \"th house is \"\r\n << cdf(nb, 12 - sales_quota) << endl;\r\n/*`[pre\r\nProbability that Pat finishes on the 12th house is 0.094596\r\nProbability of selling his quota of 5 candy bars\r\non or before the 12th house is 0.56182\r\n]\r\nFinally consider the risk of Pat not selling his quota of 5 bars\r\neven after visiting all the houses.\r\nCalculate the probability that he /will/ sell on\r\nor before the last house:\r\nCalculate the probability that he would sell all his quota on the very last house.\r\n*/\r\n cout << \"Probability that Pat finishes on the \" << all_houses\r\n << \" house is \" << pdf(nb, all_houses - sales_quota) << endl;\r\n/*`\r\nProbability of selling his quota of 5 bars on the 30th house is\r\n[pre\r\nProbability that Pat finishes on the 30 house is 0.00069145\r\n]\r\nwhen he'd be very unlucky indeed!\r\n\r\nWhat is the probability that Pat exhausts all 30 houses in the neighborhood,\r\nand *still* doesn't sell the required 5 candy bars?\r\n*/\r\n cout << \"\\nProbability of selling his quota of \" << sales_quota\r\n << \" bars\\non or before the \" << all_houses << \"th house is \"\r\n << cdf(nb, all_houses - sales_quota) << endl;\r\n/*`\r\n[pre\r\nProbability of selling his quota of 5 bars\r\non or before the 30th house is 0.99849\r\n]\r\n\r\nSo the risk of failing even after visiting all the houses is 1 - this probability,\r\n ``1 - cdf(nb, all_houses - sales_quota``\r\nBut using this expression may cause serious inaccuracy,\r\nso it would be much better to use the complement of the cdf:\r\nSo the risk of failing even at, or after, the 31th (non-existent) houses is 1 - this probability,\r\n ``1 - cdf(nb, all_houses - sales_quota)``\r\nBut using this expression may cause serious inaccuracy.\r\nSo it would be much better to use the __complement of the cdf (see __why_complements).\r\n*/\r\n cout << \"\\nProbability of failing to sell his quota of \" << sales_quota\r\n << \" bars\\neven after visiting all \" << all_houses << \" houses is \"\r\n << cdf(complement(nb, all_houses - sales_quota)) << endl;\r\n/*`\r\n[pre\r\nProbability of failing to sell his quota of 5 bars\r\neven after visiting all 30 houses is 0.0015101\r\n]\r\nWe can also use the quantile (percentile), the inverse of the cdf, to\r\npredict which house Pat will finish on. So for the 8th house:\r\n*/\r\n double p = cdf(nb, (8 - sales_quota));\r\n cout << \"Probability of meeting sales quota on or before 8th house is \"<< p << endl;\r\n/*`\r\n[pre\r\nProbability of meeting sales quota on or before 8th house is 0.174\r\n]\r\n*/\r\n cout << \"If the confidence of meeting sales quota is \" << p\r\n << \", then the finishing house is \" << quantile(nb, p) + sales_quota << endl;\r\n\r\n cout<< \" quantile(nb, p) = \" << quantile(nb, p) << endl;\r\n/*`\r\n[pre\r\nIf the confidence of meeting sales quota is 0.17367, then the finishing house is 8\r\n]\r\nDemanding absolute certainty that all 5 will be sold,\r\nimplies an infinite number of trials.\r\n(Of course, there are only 30 houses on the estate,\r\nso he can't ever be *certain* of selling his quota).\r\n*/\r\n cout << \"If the confidence of meeting sales quota is \" << 1.\r\n << \", then the finishing house is \" << quantile(nb, 1) + sales_quota << endl;\r\n // 1.#INF == infinity.\r\n/*`[pre\r\nIf the confidence of meeting sales quota is 1, then the finishing house is 1.#INF\r\n]\r\nAnd similarly for a few other probabilities:\r\n*/\r\n cout << \"If the confidence of meeting sales quota is \" << 0.\r\n << \", then the finishing house is \" << quantile(nb, 0.) + sales_quota << endl;\r\n\r\n cout << \"If the confidence of meeting sales quota is \" << 0.5\r\n << \", then the finishing house is \" << quantile(nb, 0.5) + sales_quota << endl;\r\n\r\n cout << \"If the confidence of meeting sales quota is \" << 1 - 0.00151 // 30 th\r\n << \", then the finishing house is \" << quantile(nb, 1 - 0.00151) + sales_quota << endl;\r\n/*`\r\n[pre\r\nIf the confidence of meeting sales quota is 0, then the finishing house is 5\r\nIf the confidence of meeting sales quota is 0.5, then the finishing house is 11.337\r\nIf the confidence of meeting sales quota is 0.99849, then the finishing house is 30\r\n]\r\n\r\nNotice that because we chose a discrete quantile policy of real,\r\nthe result can be an 'unreal' fractional house.\r\n\r\nIf the opposite is true, we don't want to assume any confidence, then this is tantamount\r\nto assuming that all the first sales_quota trials will be successful sales.\r\n*/\r\n cout << \"If confidence of meeting quota is zero\\n(we assume all houses are successful sales)\"\r\n \", then finishing house is \" << sales_quota << endl;\r\n/*`\r\n[pre\r\nIf confidence of meeting quota is zero (we assume all houses are successful sales), then finishing house is 5\r\nIf confidence of meeting quota is 0, then finishing house is 5\r\n]\r\nWe can list quantiles for a few probabilities:\r\n*/\r\n\r\n double ps[] = {0., 0.001, 0.01, 0.05, 0.1, 0.5, 0.9, 0.95, 0.99, 0.999, 1.};\r\n // Confidence as fraction = 1-alpha, as percent = 100 * (1-alpha[i]) %\r\n cout.precision(3);\r\n for (unsigned i = 0; i < sizeof(ps)/sizeof(ps[0]); i++)\r\n {\r\n cout << \"If confidence of meeting quota is \" << ps[i]\r\n << \", then finishing house is \" << quantile(nb, ps[i]) + sales_quota\r\n << endl;\r\n }\r\n\r\n/*`\r\n[pre\r\nIf confidence of meeting quota is 0, then finishing house is 5\r\nIf confidence of meeting quota is 0.001, then finishing house is 5\r\nIf confidence of meeting quota is 0.01, then finishing house is 5\r\nIf confidence of meeting quota is 0.05, then finishing house is 6.2\r\nIf confidence of meeting quota is 0.1, then finishing house is 7.06\r\nIf confidence of meeting quota is 0.5, then finishing house is 11.3\r\nIf confidence of meeting quota is 0.9, then finishing house is 17.8\r\nIf confidence of meeting quota is 0.95, then finishing house is 20.1\r\nIf confidence of meeting quota is 0.99, then finishing house is 24.8\r\nIf confidence of meeting quota is 0.999, then finishing house is 31.1\r\nIf confidence of meeting quota is 1, then finishing house is 1.#INF\r\n]\r\n\r\nWe could have applied a ceil function to obtain a 'worst case' integer value for house.\r\n``ceil(quantile(nb, ps[i]))``\r\n\r\nOr, if we had used the default discrete quantile policy, integer_outside, by omitting\r\n``#define BOOST_MATH_DISCRETE_QUANTILE_POLICY real``\r\nwe would have achieved the same effect.\r\n\r\nThe real result gives some suggestion which house is most likely.\r\nFor example, compare the real and integer_outside for 95% confidence.\r\n\r\n[pre\r\nIf confidence of meeting quota is 0.95, then finishing house is 20.1\r\nIf confidence of meeting quota is 0.95, then finishing house is 21\r\n]\r\nThe real value 20.1 is much closer to 20 than 21, so integer_outside is pessimistic.\r\nWe could also use integer_round_nearest policy to suggest that 20 is more likely.\r\n\r\nFinally, we can tabulate the probability for the last sale being exactly on each house.\r\n*/\r\n cout << \"\\nHouse for \" << sales_quota << \"th (last) sale. Probability (%)\" << endl;\r\n cout.precision(5);\r\n for (int i = (int)sales_quota; i < all_houses+1; i++)\r\n {\r\n cout << left << setw(3) << i << \" \" << setw(8) << cdf(nb, i - sales_quota) << endl;\r\n }\r\n cout << endl;\r\n/*`\r\n[pre\r\nHouse for 5 th (last) sale. Probability (%)\r\n5 0.01024\r\n6 0.04096\r\n7 0.096256\r\n8 0.17367\r\n9 0.26657\r\n10 0.3669\r\n11 0.46723\r\n12 0.56182\r\n13 0.64696\r\n14 0.72074\r\n15 0.78272\r\n16 0.83343\r\n17 0.874\r\n18 0.90583\r\n19 0.93039\r\n20 0.94905\r\n21 0.96304\r\n22 0.97342\r\n23 0.98103\r\n24 0.98655\r\n25 0.99053\r\n26 0.99337\r\n27 0.99539\r\n28 0.99681\r\n29 0.9978\r\n30 0.99849\r\n]\r\n\r\nAs noted above, using a catch block is always a good idea, even if you do not expect to use it.\r\n*/\r\n }\r\n catch(const std::exception& e)\r\n { // Since we have set an overflow policy of ignore_error,\r\n // an overflow exception should never be thrown.\r\n std::cout << \"\\nMessage from thrown exception was:\\n \" << e.what() << std::endl;\r\n/*`\r\nFor example, without a ignore domain error policy, if we asked for ``pdf(nb, -1)`` for example, we would get:\r\n[pre\r\nMessage from thrown exception was:\r\n Error in function boost::math::pdf(const negative_binomial_distribution&, double):\r\n Number of failures argument is -1, but must be >= 0 !\r\n]\r\n*/\r\n//] [/ negative_binomial_eg1_2]\r\n }\r\n return 0;\r\n} // int main()\r\n\r\n\r\n/*\r\n\r\nOutput is:\r\n\r\nSelling candy bars - using the negative binomial distribution.\r\nby Dr. Diane Evans,\r\nProfessor of Mathematics at Rose-Hulman Institute of Technology,\r\nsee http://en.wikipedia.org/wiki/Negative_binomial_distribution\r\nPat has a sales per house success rate of 0.4.\r\nTherefore he would, on average, sell 40 bars after trying 100 houses.\r\nWith a success rate of 0.4, he might expect, on average,\r\nto need to visit about 12 houses in order to sell all 5 bars.\r\nProbability that Pat finishes on the 5th house is 0.01024\r\nProbability that Pat finishes on the 6th house is 0.03072\r\nProbability that Pat finishes on the 7th house is 0.055296\r\nProbability that Pat finishes on the 8th house is 0.077414\r\nProbability that Pat finishes on or before the 8th house is sum\r\npdf(sales_quota) + pdf(6) + pdf(7) + pdf(8) = 0.17367\r\nProbability of selling his quota of 5 bars\r\non or before the 8th house is 0.17367\r\nProbability that Pat finishes exactly on the 10th house is 0.10033\r\nProbability of selling his quota of 5 bars\r\non or before the 10th house is 0.3669\r\nProbability that Pat finishes exactly on the 11th house is 0.10033\r\nProbability of selling his quota of 5 bars\r\non or before the 11th house is 0.46723\r\nProbability that Pat finishes exactly on the 12th house is 0.094596\r\nProbability of selling his quota of 5 bars\r\non or before the 12th house is 0.56182\r\nProbability that Pat finishes on the 30 house is 0.00069145\r\nProbability of selling his quota of 5 bars\r\non or before the 30th house is 0.99849\r\nProbability of failing to sell his quota of 5 bars\r\neven after visiting all 30 houses is 0.0015101\r\nProbability of meeting sales quota on or before 8th house is 0.17367\r\nIf the confidence of meeting sales quota is 0.17367, then the finishing house is 8\r\n quantile(nb, p) = 3\r\nIf the confidence of meeting sales quota is 1, then the finishing house is 1.#INF\r\nIf the confidence of meeting sales quota is 0, then the finishing house is 5\r\nIf the confidence of meeting sales quota is 0.5, then the finishing house is 11.337\r\nIf the confidence of meeting sales quota is 0.99849, then the finishing house is 30\r\nIf confidence of meeting quota is zero\r\n(we assume all houses are successful sales), then finishing house is 5\r\nIf confidence of meeting quota is 0, then finishing house is 5\r\nIf confidence of meeting quota is 0.001, then finishing house is 5\r\nIf confidence of meeting quota is 0.01, then finishing house is 5\r\nIf confidence of meeting quota is 0.05, then finishing house is 6.2\r\nIf confidence of meeting quota is 0.1, then finishing house is 7.06\r\nIf confidence of meeting quota is 0.5, then finishing house is 11.3\r\nIf confidence of meeting quota is 0.9, then finishing house is 17.8\r\nIf confidence of meeting quota is 0.95, then finishing house is 20.1\r\nIf confidence of meeting quota is 0.99, then finishing house is 24.8\r\nIf confidence of meeting quota is 0.999, then finishing house is 31.1\r\nIf confidence of meeting quota is 1, then finishing house is 1.#J\r\nHouse for 5th (last) sale. Probability (%)\r\n5 0.01024\r\n6 0.04096\r\n7 0.096256\r\n8 0.17367\r\n9 0.26657\r\n10 0.3669\r\n11 0.46723\r\n12 0.56182\r\n13 0.64696\r\n14 0.72074\r\n15 0.78272\r\n16 0.83343\r\n17 0.874\r\n18 0.90583\r\n19 0.93039\r\n20 0.94905\r\n21 0.96304\r\n22 0.97342\r\n23 0.98103\r\n24 0.98655\r\n25 0.99053\r\n26 0.99337\r\n27 0.99539\r\n28 0.99681\r\n29 0.9978\r\n30 0.99849\r\n\r\n*/\r\n", "meta": {"hexsha": "ce526141a2a2dcbcffb4a58f6d090ee20d23bd05", "size": 22612, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/libs/math/example/negative_binomial_example1.cpp", "max_stars_repo_name": "Jackarain/tinyrpc", "max_stars_repo_head_hexsha": "07060e3466776aa992df8574ded6c1616a1a31af", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "third_party/boost/libs/math/example/negative_binomial_example1.cpp", "max_issues_repo_name": "avplayer/cxxrpc", "max_issues_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "third_party/boost/libs/math/example/negative_binomial_example1.cpp", "max_forks_repo_name": "avplayer/cxxrpc", "max_forks_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 43.9922178988, "max_line_length": 118, "alphanum_fraction": 0.6551830886, "num_tokens": 5739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8740772351648677, "lm_q1q2_score": 0.7698846746602018}} {"text": "#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nvoid clearInputBuffer();\r\nint mainMenu();\r\ndouble getNumber();\r\nvoid getNumbers(std::vector & nums);\r\nchar getOperation();\r\nint getStatisticalAverage();\r\nint getEquationType();\r\nstd::pair calculateRootsOfQuadratic(double a, double b, double discriminant);\r\n\r\nint main() {\r\n\tstd::cout << \"Welcome to my calculator!\\n\";\r\n\twhile(true) {\r\n\t\tint function{ mainMenu() };\r\n\t\tif(function == 1) {\r\n\t\t\tdouble firstNumber{ getNumber() };\r\n\t\t\tchar operation{ getOperation() };\r\n\t\t\tdouble secondNumber{ 0 };\r\n\r\n\t\t\tif(operation != '!') {\r\n\t\t\t\tsecondNumber = getNumber();\r\n\t\t\t}\r\n\t\t\tswitch(operation) {\r\n\t\t\tcase '+':\r\n\t\t\t\tstd::cout << firstNumber << \" + \" << secondNumber << \" = \" << firstNumber + secondNumber << \"\\n\\n\";\r\n\t\t\t\tbreak;\r\n\t\t\tcase '-':\r\n\t\t\t\tstd::cout << firstNumber << \" - \" << secondNumber << \" = \" << firstNumber - secondNumber << \"\\n\\n\";\r\n\t\t\t\tbreak;\r\n\t\t\tcase '*':\r\n\t\t\t\tstd::cout << firstNumber << \" * \" << secondNumber << \" = \" << firstNumber * secondNumber << \"\\n\\n\";\r\n\t\t\t\tbreak;\r\n\t\t\tcase '/':\r\n\t\t\t\tif(secondNumber) {\r\n\t\t\t\t\tstd::cout << firstNumber << \" / \" << secondNumber << \" = \" << firstNumber / secondNumber << \"\\n\\n\";\r\n\t\t\t\t} else {\r\n\t\t\t\t\tstd::cout << \"Illegal operation! Cannont divide by 0.\\n\\n\";\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase '^':\r\n\t\t\t\tstd::cout << firstNumber << \" ^ \" << secondNumber << \" = \" << pow(firstNumber, secondNumber) << \"\\n\\n\";\r\n\t\t\t\tbreak;\r\n\t\t\tcase '!':\r\n\t\t\t\tif(std::floor(firstNumber) == firstNumber && firstNumber >= 0) {\r\n\t\t\t\t\tstd::cout << firstNumber << \"! = \" << std::fixed << static_cast(boost::math::factorial(static_cast(firstNumber))) << \"\\n\\n\";\r\n\t\t\t\t} else {\r\n\t\t\t\t\tstd::cout << \"The number must be an integer!\\n\\n\";\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase '%':\r\n\t\t\t\tstd::cout << firstNumber << \"% of \" << secondNumber << \" = \" << firstNumber / 100 * secondNumber << \"\\n\\n\";\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t} else if(function == 2) {\r\n\t\t\tint statisticalAverage{ getStatisticalAverage() };\r\n\t\t\tif(statisticalAverage == 1) {\r\n\t\t\t\tstd::vector nums;\r\n\t\t\t\tgetNumbers(nums);\r\n\t\t\t\tdouble sum{ 0 };\r\n\r\n\t\t\t\tfor(double x : nums) {\r\n\t\t\t\t\tsum += x;\r\n\t\t\t\t}\r\n\t\t\t\tstd::cout << \"The mean is \" << sum / nums.size() << '\\n';\r\n\t\t\t} else if(statisticalAverage == 2) {\r\n\t\t\t\tstd::vector nums;\r\n\t\t\t\tgetNumbers(nums);\r\n\t\t\t\tsort(nums.begin(), nums.end());\r\n\t\t\t\tif(nums.size() % 2) {\r\n\t\t\t\t\tstd::cout << \"The median is: \" << nums[nums.size() / 2] << '\\n';\r\n\t\t\t\t} else {\r\n\t\t\t\t\tstd::cout << \"The median is: \" << (nums[nums.size() / 2 - 1] + nums[nums.size() / 2]) / 2 << '\\n';\r\n\t\t\t\t}\r\n\t\t\t} else if(statisticalAverage == 3) {\r\n\t\t\t\tstd::vector nums;\r\n\t\t\t\tgetNumbers(nums);\r\n\t\t\t\tsort(nums.begin(), nums.end());\r\n\t\t\t\tdouble mode{ 0 };\r\n\t\t\t\tdouble element{ nums[0] };\r\n\t\t\t\tint noOfOccurrencesOfMode{ 0 };\r\n\t\t\t\tint noOfElement{ 0 };\r\n\r\n\t\t\t\tfor(int i{ 0 }; i < nums.size(); i++) {\r\n\t\t\t\t\tif(nums[i] == element) {\r\n\t\t\t\t\t\tnoOfElement++;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tif(noOfElement > noOfOccurrencesOfMode) {\r\n\t\t\t\t\t\t\tmode = element;\r\n\t\t\t\t\t\t\tnoOfOccurrencesOfMode = noOfElement;\r\n\t\t\t\t\t\t\tnoOfElement = 1;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telement = nums[i];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif(noOfElement > noOfOccurrencesOfMode) {\r\n\t\t\t\t\tmode = element;\r\n\t\t\t\t}\r\n\t\t\t\tstd::cout << \"The mode is: \" << mode << '\\n';\r\n\t\t\t} else {\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\t\t\tclearInputBuffer();\r\n\t\t} else {\r\n\t\t\tint equationType{ getEquationType() };\r\n\t\t\tif(equationType == 1) {\r\n\t\t\t\tstd::cout << \"Make sure the equation is in the form ax^2 + bx + c = 0\\n\";\r\n\t\t\t\tstd::cout << \"Enter a, b, and c:\\n\";\r\n\t\t\t\tdouble a, b, c;\r\n\r\n\t\t\t\twhile(!(std::cin >> a >> b >> c)) {\r\n\t\t\t\t\tstd::cout << \"Please enter numbers for a, b, and c.\\n\";\r\n\t\t\t\t\tclearInputBuffer();\r\n\t\t\t\t}\r\n\t\t\t\tdouble discriminant{ b * b - 4 * a * c };\r\n\t\t\t\tstd::pair x{ calculateRootsOfQuadratic(a, b, discriminant).first, calculateRootsOfQuadratic(a, b, discriminant).second };\r\n\t\t\t\tif(discriminant > 0) {\r\n\t\t\t\t\tstd::cout << \"x1 = \" << x.first << \" x2 = \" << x.second << '\\n';\r\n\t\t\t\t} else if(!discriminant) {\r\n\t\t\t\t\tstd::cout << \"x = \" << x.first << '\\n';\r\n\t\t\t\t} else {\r\n\t\t\t\t\tstd::cout << \"x1 = \" << x.first << \" + \" << x.second << \"i\\n\";\r\n\t\t\t\t\tstd::cout << \"x2 = \" << x.first << \" - \" << x.second << \"i\\n\";\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid clearInputBuffer() {\r\n\tstd::cin.clear();\r\n\tstd::cin.ignore(std::numeric_limits::max(), '\\n');\r\n}\r\n\r\nint mainMenu() {\r\n\tint input;\r\n\tstd::cout << \"\\n1. Arithmetic mode\\n2. Statistical average mode\\n3. Equation solver mode\\n4. Quit\\n\\n\";\r\n\tstd::cout << \"Enter your choice: \";\r\n\r\n\twhile(!(std::cin >> input) || (input != 1 && input != 2 && input != 3 && input != 4)) {\r\n\t\tstd::cout << \"Invalid Input! Please try again: \";\r\n\t\tclearInputBuffer();\r\n\t}\r\n\treturn input;\r\n}\r\n\r\ndouble getNumber() {\r\n\tdouble input;\r\n\tstd::cout << \"Enter a number: \";\r\n\r\n\twhile(!(std::cin >> input)) {\r\n\t\tstd::cout << \"Invalid Input! Please try again: \";\r\n\t\tclearInputBuffer();\r\n\t}\r\n\treturn input;\r\n}\r\n\r\nvoid getNumbers(std::vector & nums) {\r\n\tchar input;\r\n\tdouble num;\r\n\tstd::cout << \"Enter the numbers (q to stop entering numbers):\\n\";\r\n\t\r\n\twhile(true) {\r\n\t\tstd::cin >> input;\r\n\t\tif(input == 'q') {\r\n\t\t\tbreak;\r\n\t\t} else {\r\n\t\t\tstd::cin.putback(input);\r\n\t\t\tif(!(std::cin >> num)) {\r\n\t\t\t\tstd::cout << \"Invalid Input! Please try again:\\n\";\r\n\t\t\t\tclearInputBuffer();\r\n\t\t\t} else {\r\n\t\t\t\tnums.push_back(num);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nchar getOperation() {\r\n\tchar input;\r\n\tstd::cout << \"Enter an operator (+, -, *, /, ^, !, or %): \";\r\n\r\n\twhile(std::cin >> input && (input != '+' && input != '-' && input != '*' && input != '/' && input != '^' && input != '!' && input != '%')) {\r\n\t\tstd::cout << \"Invalid Input! Please try again: \";\r\n\t\tclearInputBuffer();\r\n\t}\r\n\treturn input;\r\n}\r\n\r\nint getStatisticalAverage() {\r\n\tint input;\r\n\tstd::cout << \"\\n1. Mean\\n2. Median\\n3. Mode\\n\\n\";\r\n\tstd::cout << \"Enter your choice: \";\r\n\r\n\twhile(!(std::cin >> input) || (input != 1 && input != 2 && input != 3)) {\r\n\t\tstd::cout << \"Invalid Input! Please try again: \";\r\n\t\tclearInputBuffer();\r\n\t}\r\n\treturn input;\r\n}\r\n\r\nint getEquationType() {\r\n\tint input;\r\n\tstd::cout << \"\\n1. Quadratic\\n\\n\";\r\n\tstd::cout << \"Enter your choice: \";\r\n\r\n\twhile(!(std::cin >> input) || (input != 1)) {\r\n\t\tstd::cout << \"Invalid Input! Please try again: \";\r\n\t\tclearInputBuffer();\r\n\t}\r\n\treturn input;\r\n}\r\n\r\nstd::pair calculateRootsOfQuadratic(double a, double b, double discriminant) {\r\n\tif(discriminant > 0) {\r\n\t\treturn std::make_pair((-b + sqrt(discriminant)) / (2 * a), (-b - sqrt(discriminant)) / (2 * a));\r\n\t} else if(!discriminant) {\r\n\t\treturn std::make_pair(-b / (2 * a), 0);\r\n\t} else {\r\n\t\treturn std::make_pair(-b / (2 * a), sqrt(-discriminant) / (2 * a));\r\n\t}\r\n}", "meta": {"hexsha": "707a58a0a2e9ef7d104a8699254aab1ba27e3732", "size": 6963, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Calculator/Calculator.cpp", "max_stars_repo_name": "InterestingError0/Calculator", "max_stars_repo_head_hexsha": "60b478195d43283b3f0385d5511a78d68dc53ffe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-02T01:24:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-02T01:24:06.000Z", "max_issues_repo_path": "Calculator/Calculator.cpp", "max_issues_repo_name": "InterestingError0/Calculator", "max_issues_repo_head_hexsha": "60b478195d43283b3f0385d5511a78d68dc53ffe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Calculator/Calculator.cpp", "max_forks_repo_name": "InterestingError0/Calculator", "max_forks_repo_head_hexsha": "60b478195d43283b3f0385d5511a78d68dc53ffe", "max_forks_repo_licenses": ["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.1428571429, "max_line_length": 217, "alphanum_fraction": 0.5526353583, "num_tokens": 1999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7698033547967159}} {"text": "#include \n#include \n\nnamespace boost{ namespace gil{\n\n/// \\defgroup ImageProcessingMath\n/// \\brief Math operations for IP algorithms\n///\n/// This is mostly handful of mathemtical\n/// operations that are required by other\n/// image processing algorithms\n\n/// \\brief Normalized cardinal sine\n/// \\ingroup ImageProcessingMath\n///\n/// normalized_sinc(x) = sin(pi * x) / (pi * x)\ndouble normalized_sinc(double x)\n{\n return std::sin(x * boost::gil::pi) / (x * boost::gil::pi);\n}\n\n/// \\brief Lanczos response at point x\n/// \\ingroup ImageProcessingMath\n///\n/// Lanczos response is defined as:\n/// x == 0: 1\n/// -a < x && x < a: 0\n/// otherwise: normalized_sinc(x) / normalized_sinc(x / a)\ndouble lanczos(double x, std::ptrdiff_t a)\n{\n if (x == 0)\n {\n return 1;\n }\n if (-a < x && x < a)\n {\n return normalized_sinc(x)\n / normalized_sinc(x / static_cast(a));\n }\n\n return 0;\n}\n}}\n", "meta": {"hexsha": "489e6cfc93e7c66ce2adc6554712337c421c6ee5", "size": 963, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/image_processing/numeric.hpp", "max_stars_repo_name": "miralshah365/gil", "max_stars_repo_head_hexsha": "ee169ef104528b99e47186a01414b02e46416812", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/gil/image_processing/numeric.hpp", "max_issues_repo_name": "miralshah365/gil", "max_issues_repo_head_hexsha": "ee169ef104528b99e47186a01414b02e46416812", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/gil/image_processing/numeric.hpp", "max_forks_repo_name": "miralshah365/gil", "max_forks_repo_head_hexsha": "ee169ef104528b99e47186a01414b02e46416812", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8863636364, "max_line_length": 63, "alphanum_fraction": 0.6220145379, "num_tokens": 262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.93812402119614, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7691616332391241}} {"text": "// Find best-fit plane to an array of points\n// adapted from https://gist.github.com/ialhashim/0a2554076a6cf32831ca\n\n#include \n#include \n\ntemplate\nstd::pair best_plane_from_points(const std::vector & c)\n{\n\t// copy coordinates to matrix in Eigen format\n\tsize_t num_atoms = c.size();\n\tEigen::Matrix< typename Vector3::Scalar, Eigen::Dynamic, Eigen::Dynamic > coord(3, num_atoms);\n\tfor (size_t i = 0; i < num_atoms; ++i) coord.col(i) = c[i];\n\n\t// calculate centroid\n\tVector3 centroid(coord.row(0).mean(), coord.row(1).mean(), coord.row(2).mean());\n\n\t// subtract centroid\n\tcoord.row(0).array() -= centroid(0);\n coord.row(1).array() -= centroid(1);\n coord.row(2).array() -= centroid(2);\n\n\t// we only need the left-singular matrix here\n\t// http://math.stackexchange.com/questions/99299/best-fitting-plane-given-a-set-of-points\n\tauto svd = coord.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV);\n\tauto plane_normal = svd.matrixU().rightCols(1);\n\treturn std::make_pair(centroid, plane_normal);\n}\n\ntemplate\nstd::pair < Vector3, Vector3 > best_line_from_points(const std::vector & c)\n{\n\t// copy coordinates to matrix in Eigen format\n\tsize_t num_atoms = c.size();\n\tEigen::Matrix< typename Vector3::Scalar, Eigen::Dynamic, Eigen::Dynamic > centers(num_atoms, 3);\n\tfor (size_t i = 0; i < num_atoms; ++i) centers.row(i) = c[i];\n\n\tVector3 origin = centers.colwise().mean();\n\tEigen::MatrixXd centered = centers.rowwise() - origin.transpose();\n\tEigen::MatrixXd cov = centered.adjoint() * centered;\n\tEigen::SelfAdjointEigenSolver eig(cov);\n\tVector3 axis = eig.eigenvectors().col(2).normalized();\n\n\treturn std::make_pair(origin, axis);\n}", "meta": {"hexsha": "a392ad158d7297505e8fc857f917cdd4419ef5e1", "size": 1739, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/bdbd/src/libcpp/fitting3d.hpp", "max_stars_repo_name": "rkent/BDBD", "max_stars_repo_head_hexsha": "c5d391da84faf5607c443078781f8b4e1c017dd5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bdbd/src/libcpp/fitting3d.hpp", "max_issues_repo_name": "rkent/BDBD", "max_issues_repo_head_hexsha": "c5d391da84faf5607c443078781f8b4e1c017dd5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bdbd/src/libcpp/fitting3d.hpp", "max_forks_repo_name": "rkent/BDBD", "max_forks_repo_head_hexsha": "c5d391da84faf5607c443078781f8b4e1c017dd5", "max_forks_repo_licenses": ["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.6444444444, "max_line_length": 97, "alphanum_fraction": 0.7142035653, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012640659996, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7688109431601903}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nnamespace mp = boost::multiprecision;\n\nint modInverse(mp::cpp_int a, mp::cpp_int m)\n{\n mp::cpp_int m0 = m;\n mp::cpp_int y = 0, x = 1;\n\n if (m == 1)\n return 0;\n\n while (a > 1)\n {\n // q is quotient\n mp::cpp_int q = a / m;\n mp::cpp_int t = m;\n\n // m is remainder now, process same as\n // Euclid's algo\n m = a % m, a = t;\n t = y;\n\n // Update y and x\n y = x - q * y;\n x = t;\n }\n\n // Make x positive\n if (x < 0)\n x += m0;\n\n return int(x);\n}\n\nint main()\n{\n int plainMessage = 35; //plain text\n int publicBase = 5; //public base known to all\n int N = 89; // modulo\n int prvKey_BOB = 8; // number Bob chooses\n int prvKey_ALICE = 13; // number Alice chooses\n\n //Bob to send Alice the encrypted message\n\n //ALice can create a public key to share with Bob\n //Alice gives Bob her pubKey_ALICE, public base and N\n mp::cpp_int pubKey_ALICE = mp::pow(mp::cpp_int(publicBase), prvKey_ALICE) % N;\n\n //Bob can create a public key with what Alice provided\n //it's also referred as the ephemeral key\n mp::cpp_int pubKey_BOB = mp::pow(mp::cpp_int(publicBase), prvKey_BOB) % N;\n\n //Bob creates encryption key from what Alice sent him, the pubKey_ALICE\n //it's also referred as the masking key/session key\n mp::cpp_int encryptionKey = mp::pow(mp::cpp_int(pubKey_ALICE), prvKey_BOB) % N;\n\n //Bob encrypts the msg and sends it to Alice along with the ephemeral key (pubKey_BOB)\n //This is where El Gamal differs from Diffi-Helman:\n // Encrpted message and the ephemeral key are shared with ALice at the same time.\n mp::cpp_int encryptedMsg = (encryptionKey * plainMessage) % N;\n\n //Alice now has the encrypted message and Bob's public key\n //ALice first needs to figure out the encryption key Bob used\n mp::cpp_int aliceFindsOutKey = mp::pow(mp::cpp_int(pubKey_BOB), prvKey_ALICE) % N;\n\n //Alice then needs to calculate the inverse the key\n mp::cpp_int aliceInversesKey = modInverse(aliceFindsOutKey, mp::cpp_int(N));\n\n //Alice can decrypt the message\n mp::cpp_int aliceDecryptsMsg = (encryptedMsg * aliceInversesKey) % N;\n\n cout << \"pubKey_BOB\" << endl\n << pubKey_BOB << endl\n << \"pubKey_ALICE\" << endl\n << pubKey_ALICE << endl\n << \"encryptionKey\" << endl\n << encryptionKey << endl\n << \"encryptedMsg\" << endl\n << encryptedMsg << endl\n << \"aliceFindsOutKey\" << endl\n << aliceFindsOutKey << endl\n << \"aliceInversesKey\" << endl\n << aliceInversesKey << endl\n << \"aliceDecryptsMsg\" << endl\n << aliceDecryptsMsg << endl\n << \"encryption is decrypted: \" << endl\n << (plainMessage ==\n aliceDecryptsMsg)\n << endl;\n\n //alternative decryption without inversing the masking key from Bob\n mp::cpp_int alternativeDecryptionOutput = (mp::pow(mp::cpp_int(pubKey_BOB), int(N - 1 - mp::cpp_int(prvKey_ALICE)))) * encryptedMsg % N;\n cout << \"alternative decryption output: \" << endl\n << alternativeDecryptionOutput << endl\n << \"encryption is decrypted: \" << endl\n << (plainMessage ==\n alternativeDecryptionOutput)\n << endl;\n\n return 0;\n}\n\n/*\nEl Gamal Encryption Notes:\n1. Compations are equivalent between DF and El Gamal \n2. Alice sticks to her public key in El Gamal. \n3. N and P are chosen by Alice. \n4. The ephemeral key must be different for every plain text\n5. Bob is required to used a different private key every time he encryptes \nso that the ephemeral key and masking key will be different. Even though the same value\nis encrypted, the cipher text would be different. \n6. El Gamal is a probabilistic encryption scheme as Bob choosing is private key plays \nthe role of randomiser. This key should be between 2 and N-2\n\nComputational Aspects: \nSquare and multiplication algorithm can be used to calculate: \n pubKey_ALICE\n pubKey_BOB\n encryptionKey\n aliceFindsOutKey\nExtended Euclidean algo to compute the inverse\n aliceInversesKey\n\nFermat's little theorem = x^p-1 = 1 mod p, where p is prime\n plainText = aliceInversesKey * encryptedMsg = pubKey_BOB^(N-1-prvKey_ALICE) *encryptedMsg mod P\n\n\n*/\n\n/*\nALternative flow: \n1. Alice computes public key (A) = g^a mod p, where a is the private key and g is the public generator\n3. Alice sends the public key, g and p to Bob \n2. Bob creates an ephemeral key, k \n3. Bob computes C1 = g^k mod p, \n4. Bob computes C2 = m * A^k mod p\n5. Alice computes x and x^-1\n x = c1 mod p and then x^-1 \n6. ALice decrypts the message\n m = c2 * x^-1 mod p\n*/", "meta": {"hexsha": "04b5973b010bf3895ab79b33e37a7ccaf9c26b6f", "size": 4841, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "elgamal.cpp", "max_stars_repo_name": "typhoonese/elgamal", "max_stars_repo_head_hexsha": "63a5df4da60b0f177df4b5c300b98d73251913f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "elgamal.cpp", "max_issues_repo_name": "typhoonese/elgamal", "max_issues_repo_head_hexsha": "63a5df4da60b0f177df4b5c300b98d73251913f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "elgamal.cpp", "max_forks_repo_name": "typhoonese/elgamal", "max_forks_repo_head_hexsha": "63a5df4da60b0f177df4b5c300b98d73251913f5", "max_forks_repo_licenses": ["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.7094594595, "max_line_length": 140, "alphanum_fraction": 0.6467671969, "num_tokens": 1349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422158380862, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.768586842242858}} {"text": "#include \n#include \n\nusing namespace Eigen;\n\ndouble mean_squared_error(VectorXd, VectorXd);\n\nint main(){\n using std::cout;\n using std::endl;\n\n VectorXd t = VectorXd::Zero(10);\n VectorXd y = VectorXd::Zero(10);\n double mse;\n\n t(2) = 1;\n y << 0.1, 0.05, 0.6, 0.0, 0.05, 0.1, 0.0, 0.1, 0.0, 0.0;\n\n mse = mean_squared_error(t, y);\n cout << \"mean squared error: \" << mse << endl;\n\n return 0;\n}\n\ndouble mean_squared_error(VectorXd t, VectorXd y){\n return (t - y).array().square().sum() / 2;\n}", "meta": {"hexsha": "f428a066be2de39ff91ebbf488ea8ef224332126", "size": 542, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch4/mean_squared_error.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "ch4/mean_squared_error.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch4/mean_squared_error.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0740740741, "max_line_length": 60, "alphanum_fraction": 0.5996309963, "num_tokens": 189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491796, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7684128766550945}} {"text": "#include \n#include \"LBFGS.h\"\n#include \n\nusing Eigen::VectorXd;\nusing namespace LBFGSpp;\nusing namespace std;\n\ndouble quadratic(const VectorXd& x, VectorXd& grad)\n{\n //compute f(x) and grad(x)\n const int n = x.size();\n VectorXd d(n);\n for (int i=0; i param;\n LBFGSSolver solver(param);\n\n VectorXd x = VectorXd::Zero(n);\n double fx; // f(x)\n int niter = solver.minimize(quadratic, x, fx);\n\n cout << niter << \" iterations\" << endl;\n cout << \"x = \\n\" << x.transpose() << endl;\n cout << \"f(x) = \" << fx << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "2e76854cecdffd51d7563c04dcf1d9b7d885d303", "size": 774, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "machine_learning/lbfgs/lbfgs_simple.cpp", "max_stars_repo_name": "vishalbelsare/cpp", "max_stars_repo_head_hexsha": "772178d911e8f90c23e9d3c1d8d32482bc397fc5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2017-11-14T03:20:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-06T09:46:17.000Z", "max_issues_repo_path": "machine_learning/lbfgs/lbfgs_simple.cpp", "max_issues_repo_name": "kunalyadav684/cpp", "max_issues_repo_head_hexsha": "3ce14b012acb2dcdf91459fb677de4bd0cb46170", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-01T22:30:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-01T22:30:50.000Z", "max_forks_repo_path": "machine_learning/lbfgs/lbfgs_simple.cpp", "max_forks_repo_name": "kunalyadav684/cpp", "max_forks_repo_head_hexsha": "3ce14b012acb2dcdf91459fb677de4bd0cb46170", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2018-02-07T22:44:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-19T10:18:16.000Z", "avg_line_length": 18.8780487805, "max_line_length": 51, "alphanum_fraction": 0.5620155039, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.768351025630628}} {"text": "#include \n#include \n#include \"Log.h\"\n\n\n#include \n#include \n\n#include \"sophus/so3.h\"\n#include \"sophus/se3.h\"\n\nint main( int argc, char** argv )\n{\n //Set the log first \n za::my_logger::logger_type log = za::my_logger::get();\n za::Log logManager; \n logManager.set_log_file(\"./log/logSophus.log\"); \n // Rotation matrix rotated 90 degrees along the Z axis\n Eigen::Matrix3d R = Eigen::AngleAxisd(M_PI/2, Eigen::Vector3d(0,0,1)).toRotationMatrix();\n \n Sophus::SO3 SO3_R(R); // Sophus::SO(3) can be constructed directly from the rotation matrix\n Sophus::SO3 SO3_v( 0, 0, M_PI/2 ); // Can also be constructed from rotation vectors\n Eigen::Quaterniond q(R); // Or quaternion\n Sophus::SO3 SO3_q( q );\n // The above expressions are all equivalent\n // When outputting SO(3), output as so(3)\n BOOST_LOG_SEV(log, za::report)<<\"SO(3) from matrix: \"< Vector6d;\n Vector6d se3 = SE3_Rt.log();\n BOOST_LOG_SEV(log, za::report)<<\"se3 = \"<\n#include \n#include \"EigenLapack.hpp\"\n\nint main(int argc, char **argv)\n{\n /* arma::mat A = arma::randu(50,50);\n arma::mat B = A.t()*A; // generate a symmetric matrix\n\n arma::vec eigval;\n arma::mat eigvec;\n\n arma::eig_sym(eigval, eigvec, B);\n\n\n // for matrices with complex elements\n\n arma::cx_mat C = arma::randu(50,50);\n arma::cx_mat D = C.t()*C;\n\n arma::vec eigval2;\n arma::cx_mat eigvec2;\n\n eig_sym(eigval2, eigvec2, D);\n\n std::cout << \"Eigen values of random 50 x 50\\n\";\n eigval2.raw_print();*/\n \n \n arma::mat A1(3,3);\n A1(0,0) = 3;\n A1(0,1) = -2;\n A1(0,2) = 4;\n A1(1,0) = -2;\n A1(1,1) = 8;\n A1(1,2) = 2;\n A1(2,0) = 4;\n A1(2,1) = 2;\n A1(2,2) = 3;\n\n arma::vec val1;\n arma::mat vec1;\n\n eig_sym(val1, vec1, A1);\n\n std::cout << \"Testing known 3 x 3 \\n\";\n A1.raw_print();\n std::cout << \"Eigen values: \\n\";\n val1.raw_print();\n\n std::cout << \"Eigen vectors: \\n\";\n vec1.raw_print();\n\n\n arma::cx_mat Acx(3,3);\n Acx(0,0) = 3;\n Acx(0,1) = -2;\n Acx(0,2) = 4;\n Acx(1,0) = -2;\n Acx(1,1) = 8;\n Acx(1,2) = 2;\n Acx(2,0) = 4;\n Acx(2,1) = 2;\n Acx(2,2) = 3;\n\n std::cout << \"Input array: \\n\";\n Acx.raw_print();\n\n {\n arma::cx_mat Ac1 = Acx;\n EVWorker ev(3);\n std::cout << \"Order = \" << ev.size << \"\\n\";\n ev.largestEigen( Ac1.memptr(), true);\n\n std::cout << \"Largest eigen value: \" << ev.eigval[0] << \"\\n\";\n {\n arma::cx_vec vec(ev.eigvec, 3, false);\n vec.raw_print();\n }\n }\n\n {\n arma::cx_mat Ac1 = Acx;\n\n EVWorker ev(3);\n std::cout << \"Order \" << ev.size << \"\\n\";\n ev.smallestEigen( Ac1.memptr(), true);\n\n std::cout << \"Smallest eigen value: \" << ev.eigval[0] << \"\\n\";\n {\n arma::cx_vec vec(ev.eigvec, 3, false);\n vec.raw_print();\n }\n }\n\n {\n arma::cx_mat Apos(3,3, arma::fill::eye);\n Apos *= 2;\n Apos += Acx;\n\n arma::cx_mat Ainv = Apos.i();\n\n std::cout << \"Matrix inverse: \\n\";\n Ainv.raw_print();\n\n EVWorker ev(3);\n arma::cx_mat Ac1 = Apos + 0.0;\n\n int stat = ev.positiveDefiniteInverse(Ac1.memptr());\n\n std::cout << \"Lapack inverse: \" << stat << \"\\n\";\n Ac1.raw_print();\n\n arma::cx_mat test = Apos * Ac1;\n test.raw_print();\n\n }\n\n\n}\n", "meta": {"hexsha": "fb2f3bcf4f45b110a386e31e93601856711aee23", "size": 2457, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/eigen/test_eig.cpp", "max_stars_repo_name": "dbekaert/fringe", "max_stars_repo_head_hexsha": "c696c3651777d8007406fbce4470a16a39948f74", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 52.0, "max_stars_repo_stars_event_min_datetime": "2020-03-29T18:57:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:35:53.000Z", "max_issues_repo_path": "tests/eigen/test_eig.cpp", "max_issues_repo_name": "dbekaert/fringe", "max_issues_repo_head_hexsha": "c696c3651777d8007406fbce4470a16a39948f74", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2020-04-12T12:11:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T06:00:21.000Z", "max_forks_repo_path": "tests/eigen/test_eig.cpp", "max_forks_repo_name": "dbekaert/fringe", "max_forks_repo_head_hexsha": "c696c3651777d8007406fbce4470a16a39948f74", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 39.0, "max_forks_repo_forks_event_min_datetime": "2020-03-29T14:39:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T02:04:27.000Z", "avg_line_length": 20.305785124, "max_line_length": 70, "alphanum_fraction": 0.4831094831, "num_tokens": 885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682085, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.768346183691737}} {"text": "/*\n * Author: Pedro Peixoto \n */\n\n#include \n#include \n#include \n#include \n\n#if SWEET_EIGEN\n#include \n#endif\n\nint main(\n\t\tint i_argc,\n\t\tchar *const i_argv[]\n)\n{\n\n#if !SWEET_EIGEN\n\tSWEETError(\"Cannot test this without Eigen library. Please compile with --eigen=enable\");\n#endif\n\n\tEigen::MatrixXcf A(3,3) ;\n\tstd::cout< ces;\n\tces.compute(A);\n\t//std::cout << \"The eigenvalues of A are:\" << std::endl << ces.eigenvalues() << std::endl;\n\n\n\tstd::complex eval[3];\n\tstd::complex evec[3][3];\n\tfor(int i=0; i<3; i++)\n\t{\n\t\teval[i]=ces.eigenvalues()[i];\n\t\tstd::cout << \"Eigenvalue \"<< i << \" : \" << eval[i] << std::endl;\n\n\t}\n\tstd::cout << \"The matrix of eigenvectors, V, is:\" << std::endl << ces.eigenvectors() << std::endl << std::endl;\n\n\t//std::complex lambda = ces.eigenvalues()[0];\n\t//std::cout << \"Consider the first eigenvalue, lambda = \" << lambda << std::endl;\n\t//Eigen vectors\n\t//Eigen::VectorXcf v = ces.eigenvectors().col(0);\n\t//std::cout << \"If v is the corresponding eigenvector, then lambda * v = \" << std::endl << lambda * v << std::endl;\n\t//std::cout << \"... and A * v = \" << std::endl << A * v << std::endl << std::endl;\n\t//std::cout << \"Finally, V * D * V^(-1) = \" << std::endl\n\t// << ces.eigenvectors() * ces.eigenvalues().asDiagonal() * ces.eigenvectors().inverse() << std::endl;\n\n\tstd::cout< I;;\n\tI=-1.0;\n\tI=std::sqrt(I);\n\tstd::cout< lambda = ces.eigenvalues()[0];\n\t//std::cout << \"Consider the first eigenvalue, lambda = \" << lambda << std::endl;\n\t//Eigen vectors\n\t//Eigen::VectorXcf v = ces.eigenvectors().col(0);\n\t//std::cout << \"If v is the corresponding eigenvector, then lambda * v = \" << std::endl << lambda * v << std::endl;\n\t//std::cout << \"... and A * v = \" << std::endl << A * v << std::endl << std::endl;\n\t//std::cout << \"Finally, V * D * V^(-1) = \" << std::endl\n\t// << ces.eigenvectors() * ces.eigenvalues().asDiagonal() * ces.eigenvectors().inverse() << std::endl;\n\n\tstd::cout<< \"Done!\"<\n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace Eigen;\n\nclass Interpolation {\npublic:\n\t// input:\n\tstatic constexpr int POINT_LIMIT = 30; // Maximum size of input point set\n\tint n; // Number of input points\n\tfloat x[POINT_LIMIT], y[POINT_LIMIT];\n\npublic:\n\t// output:\n\tstatic constexpr float LEFT_LIMIT = 0.f; // Left end of sampling interval\n\tstatic constexpr float RIGHT_LIMIT = 10.f; // Right end of sampling interval\n\tstatic constexpr float SAMPLE_RATE = 0.05f; // Distance of adjoining sample points\n\tstatic constexpr int SAMPLE_POINTS = static_cast((RIGHT_LIMIT - LEFT_LIMIT) / SAMPLE_RATE) + 1; // Number of total sample points\n\tfloat out_x[SAMPLE_POINTS], out_y[SAMPLE_POINTS];\n\n\tInterpolation(int num, const float *ix, const float *iy) {\n\t\tn = num;\n\t\tmemcpy_s(x, num * sizeof(float), ix, num * sizeof(float));\n\t\tmemcpy_s(y, num * sizeof(float), iy, num * sizeof(float));\n\t\tmemset(out_y, 0, sizeof(float) * SAMPLE_POINTS);\n\t\tfor (int i = 0; i < SAMPLE_POINTS; ++i) {\n\t\t\tout_x[i] = (LEFT_LIMIT + i * SAMPLE_RATE);\n\t\t}\n\t}\n\n\tvoid outputToCSV(const char *filename, std::string title = \"\") { // output results to CSV\n\t\tstd::ofstream csv(filename, std::ios::out | std::ios::app);\n\t\tcsv << title << \",\";\n\t\tfor (int i = 0; i < SAMPLE_POINTS; ++i) {\n\t\t\tcsv << out_y[i] << char(i == SAMPLE_POINTS - 1 ? '\\n' : ',');\n\t\t}\n\n\t\tcsv.close();\n\t}\n\n\tvirtual void evaluate() = 0; // interpolate\n};\n\nclass LinearInterpolation : public Interpolation {\npublic:\n\tLinearInterpolation(int num, const float *ix, const float *iy) : Interpolation(num, ix, iy) {}\n\n\tvoid evaluate() final {\n\t\tint k = -1;\n\t\tfor (int i = 0; i < SAMPLE_POINTS; ++i) {\n\t\t\twhile (k + 1 < n && x[k + 1] < out_x[i]) ++k;\n\t\t\tif (k == -1 || out_x[i] > x[n - 1]) {\n\t\t\t\tout_y[i] = 0.0f;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfloat fact = (out_x[i] - x[k]) / (x[k + 1] - x[k]);\n\t\t\t\tout_y[i] = fact * y[k + 1] + (1.0f - fact) * y[k];\n\t\t\t}\n\t\t}\n\t}\n};\n\nclass LagrangeInterpolation : public Interpolation {\npublic:\n\tLagrangeInterpolation(int num, const float *ix, const float *iy) : Interpolation(num, ix, iy) {}\n\n\tvoid evaluate() final {\n\t\tfor (int h = 0; h < SAMPLE_POINTS; ++h) {\n\t\t\tfloat res = 0.0f;\n\t\t\tfor (int i = 0; i < n; ++i) {\n\t\t\t\tfloat tmp = y[i];\n\t\t\t\tfor (int j = 0; j < n; ++j) {\n\t\t\t\t\tif (i != j) {\n\t\t\t\t\t\ttmp = tmp * (out_x[h] - x[j]);\n\t\t\t\t\t\ttmp = tmp / (x[i] - x[j]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tres += tmp;\n\t\t\t}\n\t\t\tout_y[h] = res;\n\t\t}\n\t}\n};\n\nclass GaussInterpolation : public Interpolation {\npublic:\n\tfloat b0, sigma;\n\tGaussInterpolation(int num, const float *ix, const float *iy, \n\t\tfloat _b0, float _sigma = 1.0f) : b0(_b0), sigma(_sigma), Interpolation(num, ix, iy) {}\n\n\tfloat gauss(float x, float x0) {\n\t\treturn std::exp(-std::pow((x - x0) / sigma, 2.0f) / 2.0f);\n\t}\n\tvoid evaluate() final {\n\t\tMatrixXf A(n, n), B(n, 1);\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\tA(i, j) = gauss(x[i], x[j]);\n\t\t\t}\n\t\t\tB(i, 0) = y[i] - b0;\n\t\t}\n\t\tMatrixXf W = A.inverse() * B;\n\t\tfor (int i = 0; i < SAMPLE_POINTS; ++i) {\n\t\t\tfloat res = b0;\n\t\t\tfor (int j = 0; j < n; ++j) {\n\t\t\t\tres += W(j, 0) * gauss(out_x[i], x[j]);\n\t\t\t}\n\t\t\tout_y[i] = res;\n\t\t}\n\t}\n};\n\nclass LeastSquareInterpolation : public Interpolation {\npublic:\n\tint m;\n\tLeastSquareInterpolation(int num, const float *ix, const float *iy, int _m) \n\t\t: m(_m), Interpolation(num, ix, iy) {}\n\n\tvoid evaluate() final {\n\t\tMatrixXf A(n, m + 1);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tfloat pow = 1.0f;\n\t\t\tfor (int j = m; j >= 0; --j) {\n\t\t\t\tA(i, j) = pow;\n\t\t\t\tpow *= x[i];\n\t\t\t}\n\t\t}\n\t\t\n\t\tMatrixXf B(n, 1);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tB(i, 0) = y[i];\n\t\t}\n\n\t\tMatrixXf W = (A.transpose() * A).inverse() * A.transpose() * B;\n\t\tfor (int i = 0; i < SAMPLE_POINTS; ++i) {\n\t\t\tfloat pow = 1.0f, res = 0.0f;\n\t\t\tfor (int j = m; j >= 0; --j) {\n\t\t\t\tres += pow * W(j, 0);\n\t\t\t\tpow *= out_x[i];\n\t\t\t}\n\t\t\tout_y[i] = res;\n\t\t}\n\t}\n};\n\nclass RidgeRegressionInterpolation : public Interpolation {\npublic:\n\tint m;\n\tfloat lambda;\n\tRidgeRegressionInterpolation(int num, const float *ix, const float *iy, \n\t\tint _m, float _lambda) : m(_m), lambda(_lambda), Interpolation(num, ix, iy) {}\n\n\tvoid evaluate() final {\n\t\tMatrixXf A(n, m + 1);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tfloat pow = 1.0f;\n\t\t\tfor (int j = m; j >= 0; --j) {\n\t\t\t\tA(i, j) = pow;\n\t\t\t\tpow *= x[i];\n\t\t\t}\n\t\t}\n\n\t\tMatrixXf B(n, 1);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tB(i, 0) = y[i];\n\t\t}\n\n\t\tMatrixXf W = (A.transpose() * A + lambda * MatrixXf::Identity(m + 1, m + 1)).inverse() * A.transpose() * B;\n\t\tfor (int i = 0; i <= m; i++) std::cout << W(i, 0) << \" \";\n\t\tfor (int i = 0; i < SAMPLE_POINTS; ++i) {\n\t\t\tfloat pow = 1.0f, res = 0.0f;\n\t\t\tfor (int j = m; j >= 0; --j) {\n\t\t\t\tres += pow * W(j, 0);\n\t\t\t\tpow *= out_x[i];\n\t\t\t}\n\t\t\tout_y[i] = res;\n\t\t}\n\t}\n};\n\n\nint main() {\n\tstd::ifstream dataflow(\"data.txt\", std::ios::in);\n\tint num;\n\tfloat x[Interpolation::POINT_LIMIT], y[Interpolation::POINT_LIMIT];\n\tdataflow >> num;\n\tfor (int i = 0; i < num; ++i) {\n\t\tdataflow >> x[i];\n\t}\n\tfor (int i = 0; i < num; ++i) {\n\t\tdataflow >> y[i];\n\t}\n\n\tdataflow.close();\n\n\tLinearInterpolation inter0(num, x, y);\n\tLagrangeInterpolation inter1(num, x, y);\n\tGaussInterpolation inter2(num, x, y, 0.0f);\n\tLeastSquareInterpolation inter3(num, x, y, 2);\n\tRidgeRegressionInterpolation inter4(num, x, y, 5, 10000.0f);\n\n\tinter0.evaluate();\n\tinter1.evaluate();\n\tinter2.evaluate();\n\tinter3.evaluate();\n\tinter4.evaluate();\n\n\tinter0.outputToCSV(\"result.csv\", \"LinearInterpolation\");\n\tinter1.outputToCSV(\"result.csv\", \"LagrangeInterpolation\");\n\tinter2.outputToCSV(\"result.csv\", \"GaussInterpolation\");\n\tinter3.outputToCSV(\"result.csv\", \"LeastSquareInterpolation\");\n\tinter4.outputToCSV(\"result.csv\", \"RidgeRegressionInterpolation\");\n\treturn 0;\n}", "meta": {"hexsha": "48585a6b431402e01f0d72dab7f4b828fec63bec", "size": 5715, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homeworks/HW1/interpolation.cpp", "max_stars_repo_name": "g1n0st/GAMES102", "max_stars_repo_head_hexsha": "44a8cf9db102109c8fd15c8dc06aa6ad1519a5eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-10-23T16:33:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T23:49:36.000Z", "max_issues_repo_path": "homeworks/HW1/interpolation.cpp", "max_issues_repo_name": "g1n0st/GAMES102", "max_issues_repo_head_hexsha": "44a8cf9db102109c8fd15c8dc06aa6ad1519a5eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/HW1/interpolation.cpp", "max_forks_repo_name": "g1n0st/GAMES102", "max_forks_repo_head_hexsha": "44a8cf9db102109c8fd15c8dc06aa6ad1519a5eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-03-18T08:45:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-17T02:36:06.000Z", "avg_line_length": 25.9772727273, "max_line_length": 134, "alphanum_fraction": 0.5860017498, "num_tokens": 1975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7680940454375383}} {"text": "// To run this script, `cd` to the `./test/fixtures` directory and then execute in the terminal `runWandbox --file --compiler gcc-head --output output.json ./runner.cpp`.\n\n#include \n#include \n#include \n\nusing namespace std;\n\nvector linspace( double start, double end, int num ) {\n\tdouble delta = (end - start) / (num - 1);\n\tvector arr( num - 1 );\n\tfor ( int i = 0; i < num - 1; ++i ){\n\t\tarr[ i ] = start + delta * i;\n\t}\n\tarr.push_back( end );\n\treturn arr;\n}\n\nvoid print_vector( vector vec, bool last = false ) {\n\tcout << \"[\";\n\tfor ( vector::iterator it = vec.begin(); it != vec.end(); ++it ) {\n\t\tif ( vec.end() != it+1 ) {\n\t\t\tcout << setprecision ( 18 ) << *it;\n\t\t\tcout << \",\";\n\t\t} else {\n\t\t\tcout << setprecision ( 18 ) << *it;\n\t\t\tcout << \"]\";\n\t\t\tif ( last == false ) {\n\t\t\t\tcout << \",\";\n\t\t\t}\n\t\t}\n\t}\n\treturn;\n}\n\nvoid print_results( vector x, vector expected ) {\n\tcout << \"{\" << endl;\n\tcout << \" \\\"x\\\": \";\n\tprint_vector( x );\n\tcout << \" \\\"expected\\\": \";\n\tprint_vector( expected, true );\n\tcout << \"}\" << endl;\n\treturn;\n}\n\nint main() {\n\tvector x = linspace( -50.0, 50.0, 2000 );\n\tvector expected;\n\n\tfor ( int i = 0; i < 2000; i++ ) {\n\t\texpected.push_back( boost::math::zeta( x[ i ] ) );\n\t}\n\tprint_results( x, expected );\n\treturn 0;\n}\n", "meta": {"hexsha": "f5aa6b9f7ea089f5f6b9b8c417f5dee77a59d352", "size": 1354, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/fixtures/runner.cpp", "max_stars_repo_name": "math-io/riemann-zeta", "max_stars_repo_head_hexsha": "9c4c3abfed8be3ad936206d54c5e64f5bdc980b6", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-03-14T02:42:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T06:22:57.000Z", "max_issues_repo_path": "test/fixtures/runner.cpp", "max_issues_repo_name": "cedric43-2718/riemann-zeta", "max_issues_repo_head_hexsha": "9c4c3abfed8be3ad936206d54c5e64f5bdc980b6", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-03-14T02:49:47.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-01T01:25:39.000Z", "max_forks_repo_path": "test/fixtures/runner.cpp", "max_forks_repo_name": "math-io/zeta", "max_forks_repo_head_hexsha": "9c4c3abfed8be3ad936206d54c5e64f5bdc980b6", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-08T05:53:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T05:53:35.000Z", "avg_line_length": 24.1785714286, "max_line_length": 170, "alphanum_fraction": 0.5790251108, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.7679457110968124}} {"text": "// c libaries\r\n#include \r\n// c++ libaries\r\n#include \r\n// eigen libraries\r\n#include \r\n// ann - optimization\r\n#include \"src/opt/optimize.hpp\"\r\n// ann - string\r\n#include \"src/str/print.hpp\"\r\n\r\n//**********************************************************************\r\n// Rosenberg function\r\n//**********************************************************************\r\n\r\nstruct Rosen{\r\n\tdouble a,b;\r\n\tRosen():a(1.0),b(100.0){};\r\n\tRosen(double aa, double bb):a(aa),b(bb){};\r\n\tdouble operator()(const Eigen::VectorXd& x, Eigen::VectorXd& g){\r\n\t\tg[0]=-2.0*(a-x[0])-4.0*b*x[0]*(x[1]-x[0]*x[0]);\r\n\t\tg[1]=2.0*b*(x[1]-x[0]*x[0]);\r\n\t\treturn (a-x[0])*(a-x[0])+b*(x[1]-x[0]*x[0])*(x[1]-x[0]*x[0]);\r\n\t};\r\n};\r\n\r\nvoid opt_rosen(Opt::Model& model){\r\n\t//rosenberg function\r\n\tRosen rosen;\r\n\t//init data\r\n\tOpt::Data data(2);\r\n\tdata.p()[0]=2.0*(1.0*std::rand()/RAND_MAX-0.5);\r\n\tdata.p()[1]=2.0*(1.0*std::rand()/RAND_MAX-0.5);\r\n\tdata.pOld()=data.p();\r\n\tdata.max()=100000;\r\n\tdata.nPrint()=100;\r\n\tdata.algo()=model.algo();\r\n\tdata.stop()=Opt::Stop::FABS;\r\n\tdata.tol()=1e-8;\r\n\t//optimize\r\n\tfor(int i=0; i\nusing namespace std;\n\n// Eigen includes\n#include \nusing namespace Eigen;\n\n// autodiff include\n#include \n#include \nusing namespace autodiff;\n\n// The vector function for which the Jacobian is needed\nVectorXdual f(const VectorXdual& x)\n{\n return x * x.sum();\n}\n\nint main()\n{\n VectorXdual x(5); // the input vector x with 5 variables\n x << 1, 2, 3, 4, 5; // x = [1, 2, 3, 4, 5]\n\n VectorXdual F; // the output vector F = f(x) evaluated together with Jacobian matrix below\n\n MatrixXd J = jacobian(f, wrt(x), at(x), F); // evaluate the output vector F and the Jacobian matrix dF/dx\n\n cout << \"F = \\n\" << F << endl; // print the evaluated output vector F\n cout << \"J = \\n\" << J << endl; // print the evaluated Jacobian matrix dF/dx\n}\n", "meta": {"hexsha": "f5f350e023316c1cc9874a1f4ee89f4983a60151", "size": 853, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/forward/example-forward-jacobian-derivatives-using-eigen.cpp", "max_stars_repo_name": "ram-nad/autodiff", "max_stars_repo_head_hexsha": "a4ea49d15ae730ddfa79c3615807285006d5e7d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-21T04:02:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T04:02:38.000Z", "max_issues_repo_path": "examples/forward/example-forward-jacobian-derivatives-using-eigen.cpp", "max_issues_repo_name": "gayatri-a-b/autodiff", "max_issues_repo_head_hexsha": "98bdfea087cb67dd6e2a1a399e90bbd7ac4eb326", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-22T07:15:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-22T07:15:49.000Z", "max_forks_repo_path": "examples/forward/example-forward-jacobian-derivatives-using-eigen.cpp", "max_forks_repo_name": "gayatri-a-b/autodiff", "max_forks_repo_head_hexsha": "98bdfea087cb67dd6e2a1a399e90bbd7ac4eb326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-02-26T13:14:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T03:52:45.000Z", "avg_line_length": 26.65625, "max_line_length": 110, "alphanum_fraction": 0.652989449, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.944176852582231, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7674905014425544}} {"text": "#include \"Utils/Math/pseudo_inverse.hpp\"\n#include \n#include \n#include \nusing namespace std;\n\nnamespace myUtils {\n\n void pseudoInverse(Eigen::MatrixXd const & matrix,\n double sigmaThreshold,\n Eigen::MatrixXd & invMatrix,\n Eigen::VectorXd * opt_sigmaOut) {\n\n if ((1 == matrix.rows()) && (1 == matrix.cols())) {\n // workaround for Eigen2\n invMatrix.resize(1, 1);\n if (matrix.coeff(0, 0) > sigmaThreshold) {\n invMatrix.coeffRef(0, 0) = 1.0 / matrix.coeff(0, 0);\n }\n else {\n invMatrix.coeffRef(0, 0) = 0.0;\n }\n if (opt_sigmaOut) {\n opt_sigmaOut->resize(1);\n opt_sigmaOut->coeffRef(0) = matrix.coeff(0, 0);\n }\n return;\n }\n\n Eigen::JacobiSVD svd(matrix, Eigen::ComputeThinU | Eigen::ComputeThinV);\n // not sure if we need to svd.sort()... probably not\n int const nrows(svd.singularValues().rows());\n Eigen::MatrixXd invS;\n invS = Eigen::MatrixXd::Zero(nrows, nrows);\n for (int ii(0); ii < nrows; ++ii) {\n if (svd.singularValues().coeff(ii) > sigmaThreshold) {\n invS.coeffRef(ii, ii) = 1.0 / svd.singularValues().coeff(ii);\n }\n else{\n // invS.coeffRef(ii, ii) = 1.0/ sigmaThreshold;\n // printf(\"sigular value is too small: %f\\n\", svd.singularValues().coeff(ii));\n }\n }\n invMatrix = svd.matrixV() * invS * svd.matrixU().transpose();\n if (opt_sigmaOut) {\n *opt_sigmaOut = svd.singularValues();\n }\n }\n\n Eigen::MatrixXd getNullSpace(const Eigen::MatrixXd & J,\n const double threshold) {\n\n Eigen::MatrixXd ret(J.cols(), J.cols());\n Eigen::MatrixXd J_pinv;\n pseudoInverse(J, threshold, J_pinv);\n ret = Eigen::MatrixXd::Identity(J.cols(), J.cols()) - J_pinv * J;\n return ret;\n }\n // JM modified threshold\n void weightedInverse(const Eigen::MatrixXd & J,\n const Eigen::MatrixXd & Winv,\n Eigen::MatrixXd & Jinv) {\n Eigen::MatrixXd lambda(J* Winv * J.transpose());\n Eigen::MatrixXd lambda_inv;\n myUtils::pseudoInverse(lambda, 0.0001, lambda_inv);\n //myUtils::pseudoInverse(lambda, 1e-6, lambda_inv);\n Jinv = Winv * J.transpose() * lambda_inv;\n }\n\n}\n", "meta": {"hexsha": "1b880cec67b4479a38fba5bdc06c3f9508b50513", "size": 2581, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Utils/Math/pseudo_inverse.cpp", "max_stars_repo_name": "shbang91/PnC", "max_stars_repo_head_hexsha": "880cbbcf96a48a93a0ab646634781e4f112a71f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Utils/Math/pseudo_inverse.cpp", "max_issues_repo_name": "shbang91/PnC", "max_issues_repo_head_hexsha": "880cbbcf96a48a93a0ab646634781e4f112a71f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Utils/Math/pseudo_inverse.cpp", "max_forks_repo_name": "shbang91/PnC", "max_forks_repo_head_hexsha": "880cbbcf96a48a93a0ab646634781e4f112a71f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3521126761, "max_line_length": 97, "alphanum_fraction": 0.5222781867, "num_tokens": 625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776496, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7674566654001724}} {"text": "#include \"writer.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n//! Sparse Matrix type. Makes using this type easier.\ntypedef Eigen::SparseMatrix SparseMatrix;\n\n//! Used for filling the sparse matrix.\ntypedef Eigen::Triplet Triplet;\n\n//! Vector type\ntypedef Eigen::VectorXd Vector;\n\n//! Our function pointer, typedef'd to make it easier to use\ntypedef double (*FunctionPointer)(double, double);\n\n//----------------poissonBegin----------------\n//! Create the Poisson matrix for 2D finite difference.\n//! @param[out] A will be the Poisson matrix (as in the exercise)\n//! @param[in] N number of elements in the x-direction\nvoid createPorousMediaMatrix2D(SparseMatrix &A, FunctionPointer sigma, int N, double dx) {\n\tstd::vector triplets;\n\tA.resize(N * N, N * N);\n\ttriplets.reserve(5 * N * N - 4 * N);\n\n\t// Fill up triples\n\n\t// (write your solution here)\n\tA.setZero();\n\tstd::array ss;\n\tauto s = [&ss](int i, int j) -> double {\n\t\tif (i == 0 && j == 0) {\n\t\t\treturn ss[0];\n\t\t} else if (i == -1 && j == 0) {\n\t\t\treturn ss[1];\n\t\t} else if (i == 1 && j == 0) {\n\t\t\treturn ss[2];\n\t\t} else if (i == 0 && j == -1) {\n\t\t\treturn ss[3];\n\t\t} else if (i == 0 && j == 1) {\n\t\t\treturn ss[4];\n\t\t} else {\n\t\t\tthrow std::runtime_error(\"s indices out of bounds.\");\n\t\t}\n\t};\n\n\tfor (int i = 0; i < N * N; i++) {\n\t\tint ii = i / N + 1;\n\t\tint jj = i % N + 1;\n\t\tss = {\n\t\t sigma(ii * dx, jj * dx),\n\t\t sigma((ii - 1) * dx, jj * dx),\n\t\t sigma((ii + 1) * dx, jj * dx),\n\t\t sigma(ii * dx, (jj - 1) * dx),\n\t\t sigma(ii * dx, (jj + 1) * dx)};\n\n\t\t// u_{i,j}\n\t\ttriplets.push_back(Triplet(i, i, 4 * s(0, 0)));\n\t\tif (i % N != 0) { // u_{i,j-1}\n\t\t\ttriplets.push_back(Triplet(i, i - 1, -1 / 4.0 * (1 * s(0, -1) + 4 * s(0, 0) - s(0, 1))));\n\t\t}\n\t\tif (i % N != N - 1) { // u_{i,j+1}\n\t\t\ttriplets.push_back(Triplet(i, i + 1, -1 / 4.0 * (-1 * s(0, -1) + 4 * s(0, 0) + s(0, 1))));\n\t\t}\n\t\tif (i >= N) { // u_{i-1,j}\n\t\t\ttriplets.push_back(Triplet(i, i - N, -1 / 4.0 * (-1 * s(-1, 0) + 4 * s(0, 0) + s(1, 0))));\n\t\t}\n\t\tif (i < N * N - N) { // u_{i+1,j}\n\t\t\ttriplets.push_back(Triplet(i, i + N, -1 / 4.0 * (1 * s(-1, 0) + 4 * s(0, 0) - s(1, 0))));\n\t\t}\n\t}\n\n\tA.setFromTriplets(triplets.begin(), triplets.end());\n}\n//----------------poissonEnd----------------\n\n//----------------RHSBegin----------------\n//! Create the Right hand side for the 2D finite difference\n//! @param[out] rhs will at the end contain the right hand side\n//! @param[in] f the right hand side function f\n//! @param[in] N the number of points in the x direction\n//! @param[in] dx the cell width\nvoid createRHS(Vector &rhs, FunctionPointer f, int N, double dx) {\n\trhs.resize(N * N);\n\n\tfor (int i = 0; i < N; ++i) {\n\t\tfor (int j = 0; j < N; ++j) {\n\t\t\tconst double x = (i + 1) * dx;\n\t\t\tconst double y = (j + 1) * dx;\n\t\t\trhs[i * N + j] = dx * dx * f(x, y);\n\t\t}\n\t}\n}\n//----------------RHSEnd----------------\n\n//----------------solveBegin----------------\n//! Solve the Poisson equation in 2D\n//! @param[in] f the function pointer to f\n//! @param[in] N the number of points to use (in x direction)\n//!\n//! @returns the approximate solution u\nVector poissonSolve(FunctionPointer f, FunctionPointer sigma, int N) {\n\tVector u;\n\tdouble dx = 1.0 / (N + 1);\n\n\t// Compute A, rhs and u\n\t// (write your solution here)\n\tSparseMatrix A;\n\tcreatePorousMediaMatrix2D(A, sigma, N, dx);\n\n\tVector rhs;\n\tcreateRHS(rhs, f, N, dx);\n\n\tEigen::SparseLU solver;\n\tsolver.compute(A);\n\n\tif (solver.info() != Eigen::Success) {\n\t\tthrow std::runtime_error(\"Could not decompose the matrix.\");\n\t}\n\n\tu.resize((N + 2) * (N + 2));\n\tu.setZero();\n\n\tVector innerU = solver.solve(rhs);\n\n\tfor (int i = 1; i < N + 1; i++) {\n\t\tfor (int j = 1; j < N + 1; j++) {\n\t\t\tu[i * (N + 2) + j] = innerU[(i - 1) * N + (j - 1)];\n\t\t}\n\t}\n\n\treturn u;\n}\n//----------------solveEnd----------------\n\n//! Gives the Right hand side F at the point x, y\ndouble F(double x, double y) {\n\treturn 4 * M_PI * M_PI * sin(2 * M_PI * x) * sin(2 * M_PI * y) * (4 * cos(2 * M_PI * x) * cos(2 * M_PI * y) + M_PI);\n}\n\n//----------------convergenceBegin----------------\n//! Gives the exact solution at the point x,y\ndouble exactSolution(double x, double y) {\n\t// (write your solution here)\n\treturn sin(2 * M_PI * x) * sin(2 * M_PI * y);\n\t//return 0; //remove when implemented\n\t//return 1.0/ (4 * M_PI * M_PI) * sin(2*M_PI*x); // constant solution\n}\n\nvoid convergeStudy(FunctionPointer F, FunctionPointer sigma) {\n\tconst int startK = 3;\n\tconst int endK = 10;\n\n\tVector errors(endK - startK);\n\tVector resolutions(errors.size());\n\tfor (int k = startK; k < endK; ++k) {\n\t\tconst int N = 1 << k; // 2^k\n\n\t\t// (write your solution here)\n\t\tresolutions[k - startK] = N;\n\t\tVector u;\n\t\tu = poissonSolve(F, sigma, N);\n\t\tdouble error = 0;\n\t\tfor (int i = 1; i < N + 2; i++) {\n\t\t\tfor (int j = 1; j < N + 2; j++) {\n\t\t\t\tdouble e = abs(u[i * (N + 2) + j] - exactSolution(i / double(N + 2), j / double(N + 2)));\n\t\t\t\tif (e > error) {\n\t\t\t\t\terror = e;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\terrors[k - startK] = error;\n\t}\n\n\twriteToFile(\"errors.txt\", errors);\n\twriteToFile(\"resolutions.txt\", resolutions);\n}\n//----------------convergenceEnd----------------\n\nint main(int, char **) {\n\tauto sigmaCos = [](double x, double y) {\n\t\treturn M_PI / 2. + cos(2 * M_PI * x) * cos(2 * M_PI * y);\n\t};\n\n\tauto sigmaConstant = [](double x, double y) {\n\t\tstd::ignore = x;\n\t\tstd::ignore = y;\n\t\treturn 1.0;\n\t};\n\tstd::ignore = sigmaConstant;\n\tauto u = poissonSolve(F, sigmaCos, 500);\n\t//auto u = poissonSolve(F, sigmaConstant, 500);\n\twriteToFile(\"u_fd.txt\", u);\n\n\tconvergeStudy(F, sigmaCos);\n}\n", "meta": {"hexsha": "ba574302ed0b10133cac3c2a13c03d967141da0c", "size": 5660, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series1/2d-FD-porous/finite_difference.cpp", "max_stars_repo_name": "westernmagic/NumPDE", "max_stars_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "series1/2d-FD-porous/finite_difference.cpp", "max_issues_repo_name": "westernmagic/NumPDE", "max_issues_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-04-01T22:52:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T16:21:55.000Z", "max_forks_repo_path": "series1/2d-FD-porous/finite_difference.cpp", "max_forks_repo_name": "westernmagic/NumPDE", "max_forks_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.881773399, "max_line_length": 117, "alphanum_fraction": 0.5524734982, "num_tokens": 1928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7673751267665115}} {"text": "/** \\file main.cpp\r\n \\brief Test and demonstration program.\r\n Copyright 2008, 2010 by Erik Schloegl \r\n */\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"MCGeneric.hpp\"\r\n#include \"QFRandom.hpp\"\r\n//#include \"MCGathererArray.hpp\"\r\n#include \"BlackScholesAsset.hpp\"\r\n\r\nusing namespace quantfin;\r\n \r\ninline double positivePart(double x)\r\n{\r\n return (x>0.0) ? x : 0.0; \r\n}\r\n\r\nclass objective_class {\r\nprivate:\r\n double initial_stock_price;\r\n double maturity;\r\n double interest_rate;\r\n double volatility;\r\n double strike;\r\n double discount_factor;\r\n double sqrt_maturity;\r\npublic:\r\n inline objective_class(double S,double T,double r,double sgm,double K)\r\n\t: initial_stock_price(S),maturity(T),interest_rate(r),volatility(sgm),strike(K),discount_factor(std::exp(-r*T)),sqrt_maturity(std::sqrt(maturity)) { };\r\n Array func(double x);\r\n};\r\n\r\n// Return discounted payoff of call and put\r\nArray objective_class::func(double x)\r\n{\r\n Array payoff(2);\r\n payoff(0) = discount_factor * positivePart(initial_stock_price*std::exp((interest_rate-0.5*volatility*volatility)*maturity+volatility*sqrt_maturity*x)-strike);\r\n payoff(1) = discount_factor * positivePart(strike-initial_stock_price*std::exp((interest_rate-0.5*volatility*volatility)*maturity+volatility*sqrt_maturity*x));\r\n return payoff;\r\n}\r\n\r\n/** Test and demonstration for finite difference schemes.\r\n\r\n Command-line arguments:\r\n -# initial stock price.\r\n The default is 100.\r\n -# interest rate.\r\n The default is 5%.\r\n -# volatility.\r\n The default is 30%. If volatility is not constant, this is the volatility for the\r\n first time segment.\r\n -# maturity.\r\n The default is 1.5.\r\n -# moneyness.\r\n The default is 1 (at the money).\r\n -# minimum MC relative accuracy.\r\n The default is 1e-2.\r\n -# maximum MC relative accuracy.\r\n The default is 1e-2.\r\n */\r\nint main(int argc,char* argv[]) \r\n{\r\n using std::cout;\r\n using std::endl;\r\n using std::flush;\r\n\r\n try {\r\n double S = 100.0;\r\n if (argc>1) S = atof(argv[1]);\r\n double r = 0.05;\r\n if (argc>2) r = atof(argv[2]);\r\n double sgm = 0.3;\r\n if (argc>3) sgm = atof(argv[3]);\r\n double mat = 1.5;\r\n if (argc>4) mat = atof(argv[4]);\r\n double K = 1.0;\r\n if (argc>5) K = atof(argv[5]);\r\n //K *= S*std::exp(r*mat);\r\n K *= S;\r\n double minacc = 1e-2;\r\n if (argc>6) minacc = atof(argv[6]);\r\n double maxacc = 1e-2;\r\n if (argc>7) maxacc = atof(argv[7]);\r\n\r\n ConstVol vol(sgm);\r\n BlackScholesAsset stock(&vol,S);\r\n cout << \"S: \" << S << \"\\nK: \" << K << \"\\nr: \" << r << \"\\nT: \" << mat << \"\\nsgm: \" << sgm << endl << endl;\r\n double CFcall = stock.option(mat,K,r);\r\n double CFput = stock.option(mat,K,r,-1);\r\n\tranlib::NormalUnit normal_RNG;\r\n\tobjective_class obj(S,mat,r,sgm,K);\r\n\tboost::function (double)> func = boost::bind(&objective_class::func,&obj,_1);\r\n\tboost::function antithetic = normal_antithetic;\r\n\tMCGeneric,ranlib::NormalUnit > mc(func,normal_RNG);\r\n\tMCGeneric,ranlib::NormalUnit > mc_antithetic(func,normal_RNG,antithetic);\r\n\tMCGatherer > mcgatherer(2),mcgatherer_antithetic(2);\r\n\tdouble acc = minacc * CFcall;\r\n\tmaxacc *= CFcall;\r\n\tcout << \"Aiming for maximum accuracy of \" << maxacc << endl;\r\n\tcout << \"Method,Option,Required accuracy,Actual accuracy,Paths,Black/Scholes value,MC value,95% CI lower bound,95% CI upper bound,Difference in standard errors\\n\";\r\n\tboost::math::normal normal;\r\n\tdouble d = boost::math::quantile(normal,0.95);\r\n\twhile (acc>=maxacc) {\r\n\t double curr_acc = mc.simulate(mcgatherer,100,acc);\r\n\t Array mean(mcgatherer.mean());\r\n\t Array stddev(mcgatherer.stddev());\r\n\t cout << \"Standard,Call,\" << acc << ',' << curr_acc << ',' << mcgatherer.number_of_simulations() << ',' << CFcall << ',' << mean(0) << ',' << mean(0)-d*stddev(0) << ',' << mean(0)+d*stddev(0) << ',' << (mean(0)-CFcall)/stddev(0) << endl;\r\n\t cout << \"Standard,Put,\" << acc << ',' << curr_acc << ',' << mcgatherer.number_of_simulations() << ',' << CFput << ',' << mean(1) << ',' << mean(1)-d*stddev(1) << ',' << mean(1)+d*stddev(1) << ',' << (mean(1)-CFput)/stddev(1) << endl;\r\n\t double curr_acc_antithetic = mc_antithetic.simulate(mcgatherer_antithetic,100,acc);\r\n\t Array mean_antithetic(mcgatherer_antithetic.mean());\r\n\t Array stddev_antithetic(mcgatherer_antithetic.stddev());\r\n\t cout << \"Antithetic,Call,\" << acc << ',' << curr_acc_antithetic << ',' << mcgatherer_antithetic.number_of_simulations() << ',' << CFcall << ',' << mean_antithetic(0) << ',' << mean_antithetic(0)-d*stddev_antithetic(0) << ',' << mean_antithetic(0)+d*stddev_antithetic(0) << ',' << (mean_antithetic(0)-CFcall)/stddev_antithetic(0) << endl;\r\n\t cout << \"Antithetic,Put,\" << acc << ',' << curr_acc_antithetic << ',' << mcgatherer_antithetic.number_of_simulations() << ',' << CFput << ',' << mean_antithetic(1) << ',' << mean_antithetic(1)-d*stddev_antithetic(1) << ',' << mean_antithetic(1)+d*stddev_antithetic(1) << ',' << (mean_antithetic(1)-CFput)/stddev_antithetic(1) << endl;\r\n\t acc /= 2; }\r\n \r\n\t} // end of try block\r\n\r\n catch (std::logic_error xcpt) {\r\n std::cerr << xcpt.what() << endl; }\r\n catch (std::runtime_error xcpt) {\r\n std::cerr << xcpt.what() << endl; }\r\n catch (...) {\r\n std::cerr << \"Other exception caught\" << endl; }\r\n \r\n return 0;\r\n}\r\n", "meta": {"hexsha": "aca7ed8efae6ef155e9b0913ef98694634e6e575", "size": 5650, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Chapter 7/MCGenericArrayTest.cpp", "max_stars_repo_name": "RoelofBerg/QuantFinCode", "max_stars_repo_head_hexsha": "a0d32b51fb46cf591242cf9981bdd86ea7b37898", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter 7/MCGenericArrayTest.cpp", "max_issues_repo_name": "RoelofBerg/QuantFinCode", "max_issues_repo_head_hexsha": "a0d32b51fb46cf591242cf9981bdd86ea7b37898", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter 7/MCGenericArrayTest.cpp", "max_forks_repo_name": "RoelofBerg/QuantFinCode", "max_forks_repo_head_hexsha": "a0d32b51fb46cf591242cf9981bdd86ea7b37898", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.803030303, "max_line_length": 341, "alphanum_fraction": 0.6332743363, "num_tokens": 1671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.767177586071806}} {"text": "\n// Copyright Christopher Kormanyos 2013.\n// Copyright Paul A. Bristow 2013.\n// Copyright John Maddock 2013.\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#ifdef _MSC_VER\n# pragma warning (disable : 4512) // assignment operator could not be generated.\n# pragma warning (disable : 4996) // assignment operator could not be generated.\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n// Weisstein, Eric W. \"Bessel Function Zeros.\" From MathWorld--A Wolfram Web Resource.\n// http://mathworld.wolfram.com/BesselFunctionZeros.html\n// Test values can be calculated using [@wolframalpha.com WolframAplha]\n// See also http://dlmf.nist.gov/10.21\n\n//[bessel_zeros_example_1\n\n/*`This example demonstrates calculating zeros of the Bessel and Neumann functions.\nIt also shows how Boost.Math and Boost.Multiprecision can be combined to provide\na many decimal digit precision. For 50 decimal digit precision we need to include\n*/\n\n #include \n\n/*`and a `typedef` for `float_type` may be convenient\n(allowing a quick switch to re-compute at built-in `double` or other precision)\n*/\n typedef boost::multiprecision::cpp_dec_float_50 float_type;\n\n//`To use the functions for finding zeros of the functions we need\n\n #include \n\n//`This file includes the forward declaration signatures for the zero-finding functions:\n\n// #include \n\n/*`but more details are in the full documentation, for example at\n[@http://www.boost.org/doc/libs/1_53_0/libs/math/doc/sf_and_dist/html/math_toolkit/special/bessel/bessel_over.html Boost.Math Bessel functions].\n*/\n\n/*`This example shows obtaining both a single zero of the Bessel function,\nand then placing multiple zeros into a container like `std::vector` by providing an iterator.\n*/\n//] [/bessel_zeros_example_1]\n\n/*The signature of the single value function is:\n\n template \n inline typename detail::bessel_traits >::result_type\n cyl_bessel_j_zero(\n T v, // Floating-point value for Jv.\n int m); // start index.\n\nThe result type is controlled by the floating-point type of parameter `v`\n(but subject to the usual __precision_policy and __promotion_policy).\n\nThe signature of multiple zeros function is:\n\n template \n inline OutputIterator cyl_bessel_j_zero(\n T v, // Floating-point value for Jv.\n int start_index, // 1-based start index.\n unsigned number_of_zeros, // How many zeros to generate\n OutputIterator out_it); // Destination for zeros.\n\nThere is also a version which allows control of the __policy_section for error handling and precision.\n\n template \n inline OutputIterator cyl_bessel_j_zero(\n T v, // Floating-point value for Jv.\n int start_index, // 1-based start index.\n unsigned number_of_zeros, // How many zeros to generate\n OutputIterator out_it, // Destination for zeros.\n const Policy& pol); // Policy to use.\n*/\n\nint main()\n{\n try\n {\n//[bessel_zeros_example_2\n\n/*`[tip It is always wise to place code using Boost.Math inside try'n'catch blocks;\nthis will ensure that helpful error messages are shown when exceptional conditions arise.]\n\nFirst, evaluate a single Bessel zero.\n\nThe precision is controlled by the float-point type of template parameter `T` of `v`\nso this example has `double` precision, at least 15 but up to 17 decimal digits (for the common 64-bit double).\n*/\n// double root = boost::math::cyl_bessel_j_zero(0.0, 1);\n// // Displaying with default precision of 6 decimal digits:\n// std::cout << \"boost::math::cyl_bessel_j_zero(0.0, 1) \" << root << std::endl; // 2.40483\n// // And with all the guaranteed (15) digits:\n// std::cout.precision(std::numeric_limits::digits10);\n// std::cout << \"boost::math::cyl_bessel_j_zero(0.0, 1) \" << root << std::endl; // 2.40482555769577\n/*`But note that because the parameter `v` controls the precision of the result,\n`v` [*must be a floating-point type].\nSo if you provide an integer type, say 0, rather than 0.0, then it will fail to compile thus:\n``\n root = boost::math::cyl_bessel_j_zero(0, 1);\n``\nwith this error message\n``\n error C2338: Order must be a floating-point type.\n``\n\nOptionally, we can use a policy to ignore errors, C-style, returning some value,\nperhaps infinity or NaN, or the best that can be done. (See __user_error_handling).\n\nTo create a (possibly unwise!) policy `ignore_all_policy` that ignores all errors:\n*/\n\n typedef boost::math::policies::policy<\n boost::math::policies::domain_error,\n boost::math::policies::overflow_error,\n boost::math::policies::underflow_error,\n boost::math::policies::denorm_error,\n boost::math::policies::pole_error,\n boost::math::policies::evaluation_error\n > ignore_all_policy;\n //`Examples of use of this `ignore_all_policy` are\n\n double inf = std::numeric_limits::infinity();\n double nan = std::numeric_limits::quiet_NaN();\n\n double dodgy_root = boost::math::cyl_bessel_j_zero(-1.0, 1, ignore_all_policy());\n std::cout << \"boost::math::cyl_bessel_j_zero(-1.0, 1) \" << dodgy_root << std::endl; // 1.#QNAN\n double inf_root = boost::math::cyl_bessel_j_zero(inf, 1, ignore_all_policy());\n std::cout << \"boost::math::cyl_bessel_j_zero(inf, 1) \" << inf_root << std::endl; // 1.#QNAN\n double nan_root = boost::math::cyl_bessel_j_zero(nan, 1, ignore_all_policy());\n std::cout << \"boost::math::cyl_bessel_j_zero(nan, 1) \" << nan_root << std::endl; // 1.#QNAN\n\n/*`Another version of `cyl_bessel_j_zero` allows calculation of multiple zeros with one call,\nplacing the results in a container, often `std::vector`.\nFor example, generate and display the first five `double` roots of J[sub v] for integral order 2,\nas column ['J[sub 2](x)] in table 1 of\n[@ http://mathworld.wolfram.com/BesselFunctionZeros.html Wolfram Bessel Function Zeros].\n*/\n unsigned int n_roots = 5U;\n std::vector roots;\n boost::math::cyl_bessel_j_zero(2.0, 1, n_roots, std::back_inserter(roots));\n std::copy(roots.begin(),\n roots.end(),\n std::ostream_iterator(std::cout, \"\\n\"));\n\n/*`Or we can use Boost.Multiprecision to generate 50 decimal digit roots of ['J[sub v]]\nfor non-integral order `v= 71/19 == 3.736842`, expressed as an exact-integer fraction\nto generate the most accurate value possible for all floating-point types.\n\nWe set the precision of the output stream, and show trailing zeros to display a fixed 50 decimal digits.\n*/\n std::cout.precision(std::numeric_limits::digits10); // 50 decimal digits.\n std::cout << std::showpoint << std::endl; // Show trailing zeros.\n\n float_type x = float_type(71) / 19;\n float_type r = boost::math::cyl_bessel_j_zero(x, 1); // 1st root.\n std::cout << \"x = \" << x << \", r = \" << r << std::endl;\n\n r = boost::math::cyl_bessel_j_zero(x, 20U); // 20th root.\n std::cout << \"x = \" << x << \", r = \" << r << std::endl;\n\n std::vector zeros;\n boost::math::cyl_bessel_j_zero(x, 1, 3, std::back_inserter(zeros));\n\n std::cout << \"cyl_bessel_j_zeros\" << std::endl;\n // Print the roots to the output stream.\n std::copy(zeros.begin(), zeros.end(),\n std::ostream_iterator(std::cout, \"\\n\"));\n//] [/bessel_zeros_example_2]\n }\n catch (std::exception const& ex)\n {\n std::cout << \"Thrown exception \" << ex.what() << std::endl;\n }\n\n } // int main()\n\n /*\n\n Output:\n\n Description: Autorun \"J:\\Cpp\\big_number\\Debug\\bessel_zeros_example_1.exe\"\n boost::math::cyl_bessel_j_zero(-1.0, 1) 3.83171\n boost::math::cyl_bessel_j_zero(inf, 1) 1.#QNAN\n boost::math::cyl_bessel_j_zero(nan, 1) 1.#QNAN\n 5.13562\n 8.41724\n 11.6198\n 14.796\n 17.9598\n \n x = 3.7368421052631578947368421052631578947368421052632, r = 7.2731751938316489503185694262290765588963196701623\n x = 3.7368421052631578947368421052631578947368421052632, r = 67.815145619696290925556791375555951165111460585458\n cyl_bessel_j_zeros\n 7.2731751938316489503185694262290765588963196701623\n 10.724858308883141732536172745851416647110749599085\n 14.018504599452388106120459558042660282427471931581\n\n*/\n\n", "meta": {"hexsha": "59172cd02153df8da4e5965bdadb33a1a5bbcd8c", "size": 8974, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/example/bessel_zeros_example_1.cpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/libs/math/example/bessel_zeros_example_1.cpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/libs/math/example/bessel_zeros_example_1.cpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 41.9345794393, "max_line_length": 144, "alphanum_fraction": 0.693670604, "num_tokens": 2419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241803, "lm_q2_score": 0.8774767826757123, "lm_q1q2_score": 0.7669824714875754}} {"text": "//\n// Functions.h\n// Functor classes for activation and activation derivative functions.\n//\n\n#include \n#include \n\n#ifndef Cynapse_Functions_h\n#define Cynapse_Functions_h\n\ndouble sigmoid(double theta) {\n return 1.0 / (1.0 + exp(-theta));\n}\n\ndouble sigmoid_derivative(double z) {\n return sigmoid(z) * (1-sigmoid(z));\n}\n\ndouble heaviside(double theta) {\n return (theta >= 0.5 ? 1.0 : 0.0);\n}\n\nEigen::MatrixXd quadratic_cost_derivative(Eigen::MatrixXd output, Eigen::MatrixXd input) {\n return output - input;\n}\n\nclass FunctionFactory\n{\npublic:\n static std::pair, std::function >\n create(const std::string& funcName) {\n \n std::function activation_func;\n std::function activation_deriv;\n \n if (funcName == \"sigmoid\") {\n activation_func = std::function(sigmoid);\n activation_deriv = std::function(sigmoid_derivative);\n }\n else if (funcName == \"step\")\n {\n activation_func = std::function(heaviside);\n }\n else\n {\n throw std::runtime_error(\"Function \" + funcName + \" is not supported.\");\n }\n \n return std::pair, std::function >(activation_func, activation_deriv);\n }\n};\n\n#endif\n", "meta": {"hexsha": "1f6bcd087571698dd5b93ec2b4d83d314985ca47", "size": 1433, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/Functions.hpp", "max_stars_repo_name": "samueljackson92/cynapse", "max_stars_repo_head_hexsha": "29bd5a50edb8b5413aca094341a52cb4c85b186c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/Functions.hpp", "max_issues_repo_name": "samueljackson92/cynapse", "max_issues_repo_head_hexsha": "29bd5a50edb8b5413aca094341a52cb4c85b186c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-10-09T16:31:03.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-30T07:06:21.000Z", "max_forks_repo_path": "src/core/Functions.hpp", "max_forks_repo_name": "samueljackson92/cynapse", "max_forks_repo_head_hexsha": "29bd5a50edb8b5413aca094341a52cb4c85b186c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0545454545, "max_line_length": 123, "alphanum_fraction": 0.6301465457, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299529686201, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7669590146370874}} {"text": "#include \n#include \n#include \n#include \n\n#include \"gramschmidt.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid test1(const MatrixXd& A)\n{\n cout << \"======================================\" << endl;\n cout << \"== Usual way to get null space of A ==\" << endl;\n cout << \"== A is m x n matrix (m >= n) ==\" << endl;\n cout << \"======================================\" << endl;\n \n HouseholderQR qr(A);\n MatrixXd R = qr.matrixQR().triangularView();\n MatrixXd Q = qr.householderQ();\n\n cout << \"=== A ===\" << endl;\n cout << A << endl;\n cout << \"=== Q ===\" << endl;\n cout << Q << endl;\n cout << \"=== R ===\" << endl;\n cout << R << endl;\n\n cout << \"=== Q*R ===\" << endl;\n cout << Q*R << endl;\n \n MatrixXd Q1 = Q.block(0,0,A.rows(),A.cols());\n MatrixXd Q2 = Q.block(0,A.cols(),A.rows(),Q.cols()-A.cols());\n\n cout << \"== Q1 ==\" << endl;\n cout << Q1 << endl;\n cout << \"== Q2 ==\" << endl;\n cout << Q2 << endl;\n\n cout << \"============================================\" << endl;\n cout << \"== Q2 is the basis of the Null Space of A ==\" << endl;\n cout << \"============================================\" << endl;\n cout << \"== A^T*Q2 ==\" << endl;\n cout << A.transpose()*Q2 << endl;\n}\n\n\nvoid test2(const MatrixXd& A)\n{\n cout << \"======================================\" << endl;\n cout << \"== Usual way to get null space of B ==\" << endl;\n cout << \"== B is m x n matrix (m <= n) ==\" << endl;\n cout << \"======================================\" << endl;\n\n MatrixXd B;\n B = A.transpose();\n\n HouseholderQR qr(B);\n MatrixXd R = qr.matrixQR().triangularView();\n MatrixXd Q = qr.householderQ();\n\n cout << \"=== B ===\" << endl;\n cout << B << endl;\n cout << \"=== Q ===\" << endl;\n cout << Q << endl;\n cout << \"=== R ===\" << endl;\n cout << R << endl;\n\n cout << \"=== Q*R ===\" << endl;\n cout << Q*R << endl;\n\n MatrixXd R1 = R.block(0,0,R.rows(),R.rows());\n MatrixXd R2 = R.block(0,R.rows(),R.rows(),R.cols()-R.rows());\n \n cout << \"== R1 ==\" << endl;\n cout << R1 << endl;\n cout << \"== R2 ==\" << endl;\n cout << R2 << endl;\n\n\n cout << \"== N is following matrix ==\" << endl;\n cout << \"=====================\" << endl;\n cout << \"== | -R1^(-1)*R2 | ==\" << endl;\n cout << \"== | I | ==\" << endl;\n cout << \"=====================\" << endl;\n MatrixXd N = MatrixXd::Zero(B.cols(),B.cols()-B.rows());\n N.block(0,0,B.rows(),B.cols()-B.rows()) = -R1.inverse()*R2;\n N.block(B.rows(),0,B.cols()-B.rows(),B.cols()-B.rows()) = MatrixXd::Identity(B.cols()-B.rows(),B.cols()-B.rows());\n cout << N << endl;\n cout << \"==============================\" << endl;\n cout << \"== N is the Null space of B ==\" << endl;\n cout << \"==============================\" << endl;\n cout << \"== B*N ==\" << endl;\n cout << B*N << endl;\n}\n\nvoid test3(const MatrixXd& A)\n{\n cout << \"==========================================\" << endl;\n cout << \"== Column pivot QR decomposition method ==\" << endl;\n cout << \"==========================================\" << endl;\n MatrixXd B = A.transpose();\n\n ColPivHouseholderQR qr(B);\n MatrixXd Q = qr.matrixQ();\n MatrixXd R = qr.matrixR().triangularView();\n MatrixXd P = qr.colsPermutation();\n\n cout << \"=== B ===\" << endl;\n cout << B << endl;\n cout << \"=== Q ===\" << endl;\n cout << Q << endl;\n cout << \"=== R ===\" << endl;\n cout << R << endl;\n cout << \"=== P ===\" << endl;\n cout << P << endl;\n\n cout << \"=== Q*R*P^T ===\" << endl;\n cout << Q*R*P.transpose() << endl;\n\n R *= P.transpose();\n \n MatrixXd R1 = R.block(0,0,R.rows(),R.rows());\n MatrixXd R2 = R.block(0,R.rows(),R.rows(),R.cols()-R.rows());\n \n cout << \"== R1 ==\" << endl;\n cout << R1 << endl;\n cout << \"== R2 ==\" << endl;\n cout << R2 << endl;\n\n cout << \"== N is following matrix ==\" << endl;\n cout << \"=====================\" << endl;\n cout << \"== | -R1^(-1)*R2 | ==\" << endl;\n cout << \"== | I | ==\" << endl;\n cout << \"=====================\" << endl;\n MatrixXd N = MatrixXd::Zero(B.cols(),B.cols()-B.rows());\n N.block(0,0,B.rows(),B.cols()-B.rows()) = -R1.inverse()*R2;\n N.block(B.rows(),0,B.cols()-B.rows(),B.cols()-B.rows()) = MatrixXd::Identity(B.cols()-B.rows(),B.cols()-B.rows());\n cout << N << endl;\n cout << \"==============================\" << endl;\n cout << \"== N is the Null space of B ==\" << endl;\n cout << \"==============================\" << endl;\n cout << \"== B*N ==\" << endl;\n cout << B*N << endl;\n \n}\n\nvoid test4(const MatrixXd& A)\n{\n cout << \"========================================\" << endl;\n cout << \"== Full pivot QR decomposition method ==\" << endl;\n cout << \"========================================\" << endl;\n MatrixXd B = A.transpose();\n\n FullPivHouseholderQR qr(B);\n MatrixXd Q = qr.matrixQ();\n MatrixXd R = qr.matrixQR().triangularView();\n MatrixXd P = qr.colsPermutation();\n\n cout << \"=== B ===\" << endl;\n cout << B << endl;\n cout << \"=== Q ===\" << endl;\n cout << Q << endl;\n cout << \"=== R ===\" << endl;\n cout << R << endl;\n cout << \"=== P ===\" << endl;\n cout << P << endl;\n\n cout << \"=== Q*R*P^T ===\" << endl;\n cout << Q*R*P.transpose() << endl;\n\n R *= P.transpose();\n \n MatrixXd R1 = R.block(0,0,R.rows(),R.rows());\n MatrixXd R2 = R.block(0,R.rows(),R.rows(),R.cols()-R.rows());\n \n cout << \"== R1 ==\" << endl;\n cout << R1 << endl;\n cout << \"== R2 ==\" << endl;\n cout << R2 << endl;\n\n cout << \"== N is following matrix ==\" << endl;\n cout << \"=====================\" << endl;\n cout << \"== | -R1^(-1)*R2 | ==\" << endl;\n cout << \"== | I | ==\" << endl;\n cout << \"=====================\" << endl;\n MatrixXd N = MatrixXd::Zero(B.cols(),B.cols()-B.rows());\n N.block(0,0,B.rows(),B.cols()-B.rows()) = -R1.inverse()*R2;\n N.block(B.rows(),0,B.cols()-B.rows(),B.cols()-B.rows()) = MatrixXd::Identity(B.cols()-B.rows(),B.cols()-B.rows());\n cout << N << endl;\n cout << \"==============================\" << endl;\n cout << \"== N is the Null space of B ==\" << endl;\n cout << \"==============================\" << endl;\n cout << \"== B*N ==\" << endl;\n cout << B*N << endl;\n}\n\nint main(void)\n{\n // Set Matrix \n MatrixXd A(6,4);\n A << \n 1, -2, 4, -8,\n 2, -1, 1, -1,\n 3, 2, 0, 3,\n 4, 1, 1, 1,\n 7, 2, 4, 8,\n 10, -4, 9, -2;\n \n test1(A);\n test2(A);\n test3(A);\n test4(A);\n \n return 0;\n}\n", "meta": {"hexsha": "a39f6a892e7c857c5da5cc72fe59ca46b65f47b1", "size": 6660, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/qr_decomposition.cpp", "max_stars_repo_name": "RyodoTanaka/eigen_example", "max_stars_repo_head_hexsha": "55da46919e02d0eb7cbea9da97ffa0f9067a6d98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/qr_decomposition.cpp", "max_issues_repo_name": "RyodoTanaka/eigen_example", "max_issues_repo_head_hexsha": "55da46919e02d0eb7cbea9da97ffa0f9067a6d98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/qr_decomposition.cpp", "max_forks_repo_name": "RyodoTanaka/eigen_example", "max_forks_repo_head_hexsha": "55da46919e02d0eb7cbea9da97ffa0f9067a6d98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-30T03:32:04.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-30T03:32:04.000Z", "avg_line_length": 30.6912442396, "max_line_length": 118, "alphanum_fraction": 0.4061561562, "num_tokens": 1925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172587090974, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7667889273302195}} {"text": "#include \n#include \n#include \n#include \n\nnamespace sm { namespace kinematics {\n\n // Euler angle rotations.\n Eigen::Matrix3d Rx(double radians){\n Eigen::Matrix3d C;\n double c = cos(radians);\n double s = sin(radians);\n C(0,0) = 1; C(0,1) = 0.0; C(0,2) = 0;\n C(1,0) = 0.0; C(1,1) = c; C(1,2) = -s;\n C(2,0) = 0.0; C(2,1) = s; C(2,2) = c;\n\t\t\n return C;\n }\n\n Eigen::Matrix3d Ry(double radians){\n Eigen::Matrix3d C;\n double c = cos(radians);\n double s = sin(radians);\n C(0,0) = c; C(0,1) = 0.0; C(0,2) = s;\n C(1,0) = 0.0; C(1,1) = 1; C(1,2) = 0.0;\n C(2,0) = -s; C(2,1) = 0.0; C(2,2) = c;\n\t\t\n return C;\n }\n Eigen::Matrix3d Rz(double radians){\n Eigen::Matrix3d C;\n double c = cos(radians);\n double s = sin(radians);\n C(0,0) = c; C(0,1) = -s; C(0,2) = 0.0;\n C(1,0) = s; C(1,1) = c; C(1,2) = 0.0;\n C(2,0) = 0.0; C(2,1) = 0.0; C(2,2) = 1;\n\t\t\n return C;\n }\n\n Eigen::Matrix3d rph2R(double x, double y, double z){\n Eigen::Matrix3d C;\n double cx = cos(x);\n double sx = sin(x);\n double cy = cos(y);\n double sy = sin(y);\n double cz = cos(z);\n double sz = sin(z);\n //[cos(z)*cos(y), -sin(z)*cos(x)+cos(z)*sin(y)*sin(x), sin(z)*sin(x)+cos(z)*sin(y)*cos(x)]\n //[sin(z)*cos(y), cos(z)*cos(x)+sin(z)*sin(y)*sin(x), -cos(z)*sin(x)+sin(z)*sin(y)*cos(x)]\n //[ -sin(y), cos(y)*sin(x), cos(y)*cos(x)]\n C(0,0) = cz*cy; C(0,1) = -sz*cx+cz*sy*sx; C(0,2) = sz*sx+cz*sy*cx;\n C(1,0) = sz*cy; C(1,1) = cz*cx+sz*sy*sx; C(1,2) = -cz*sx+sz*sy*cx;\n C(2,0) = -sy; C(2,1) = cy*sx; C(2,2) = cy*cx;\n\n return C;\n }\n Eigen::Matrix3d rph2R(Eigen::Vector3d const & x){\n return rph2R(x[0],x[1],x[2]);\n }\n\n Eigen::Vector3d R2rph(Eigen::Matrix3d const & C){\n double phi = asin(C(2,0));\n double theta = atan2(C(2,1),C(2,2));\n double psi = atan2(C(1,0), C(0,0));\n \n Eigen::Vector3d ret;\n ret[0] = theta;\n ret[1] = -phi;\n ret[2] = psi;\n\n return ret;\n }\n\t\n\n //// Small angle approximation.\n template \n Eigen::Matrix crossMx(Scalar_ x, Scalar_ y, Scalar_ z){\n Eigen::Matrix C;\n C(0,0) = 0.0; C(0,1) = -z; C(0,2) = y;\n C(1,0) = z; C(1,1) = 0.0; C(1,2) = -x;\n C(2,0) = -y; C(2,1) = x; C(2,2) = 0.0;\n return C;\n }\n template Eigen::Matrix crossMx(double x, double y, double z);\n template Eigen::Matrix crossMx(float x, float y, float z);\n\n template Eigen::Matrix crossMx(Eigen::MatrixBase > const &);\n template Eigen::Matrix crossMx(Eigen::MatrixBase > const &);\n\n template Eigen::Matrix crossMx(Eigen::MatrixBase > const &);\n template Eigen::Matrix crossMx(Eigen::MatrixBase > const &);\n\n // Axis Angle rotation.\n Eigen::Matrix3d axisAngle2R(double a, double ax, double ay, double az){\n\t\n SM_ASSERT_LT_DBG(std::runtime_error,fabs(sqrt(ax*ax + ay*ay + az*az) - 1.0), 1e-4, \"The axis is not a unit vector. ||a|| = \" << (sqrt(ax*ax + ay*ay + az*az)));\n\t\t\n if(a < 1e-12)\n return Eigen::Matrix3d::Identity();\n // e = [ax ay az]\n // e*(e') + (eye(3) - e*(e'))*cos(a) - crossMx(e) * sin(a) = \n //[ ax^2+ca*(1-ax^2), ax*ay-ca*ax*ay+sa*az, ax*az-ca*ax*az-sa*ay]\n //[ ax*ay-ca*ax*ay-sa*az, ay^2+ca*(1-ay^2), ay*az-ca*ay*az+sa*ax]\n //[ ax*az-ca*ax*az+sa*ay, ay*az-ca*ay*az-sa*ax, az^2+ca*(1-az^2)]\n double sa = sin(a);\n double ca = cos(a);\n double ax2 = ax*ax;\n double ay2 = ay*ay;\n double az2 = az*az;\n double const one = double(1);\n\n Eigen::Matrix3d C;\n C(0,0) = ax2+ca*(one-ax2); C(0,1) = ax*ay-ca*ax*ay+sa*az; C(0,2) = ax*az-ca*ax*az-sa*ay;\n C(1,0) = ax*ay-ca*ax*ay-sa*az; C(1,1) = ay2+ca*(one-ay2); C(1,2) = ay*az-ca*ay*az+sa*ax;\n C(2,0) = ax*az-ca*ax*az+sa*ay; C(2,1) = ay*az-ca*ay*az-sa*ax; C(2,2) = az2+ca*(one-az2);\n\n return C;\n }\n Eigen::Matrix3d axisAngle2R(double x, double y, double z) {\n double a = sqrt(x*x + y*y + z*z);\n if(a < 1e-12)\n return Eigen::Matrix3d::Identity();\n\t\t\n double d = 1/a;\n return axisAngle2R(a,x*d, y*d, z*d);\n }\n\n Eigen::Matrix3d axisAngle2R(Eigen::Vector3d const & x){\n return axisAngle2R(x[0], x[1], x[2]);\n }\n\t\n Eigen::Vector3d R2AxisAngle(Eigen::Matrix3d const & C){\n // Sometimes, because of roundoff error, the value of tr ends up outside\n // the valid range of arccos. Truncate to the valid range.\n double tr = std::max(-1.0, std::min( (C(0,0) + C(1,1) + C(2,2) - 1.0) * 0.5, 1.0));\n double a = acos( tr ) ;\n\n Eigen::Vector3d axis;\n\n if(fabs(a) < 1e-10) {\n return Eigen::Vector3d::Zero();\n }\n\t\t\n axis[0] = (C(2,1) - C(1,2));\n axis[1] = (C(0,2) - C(2,0));\n axis[2] = (C(1,0) - C(0,1));\n double n2 = axis.norm();\n if(fabs(n2) < 1e-10)\n return Eigen::Vector3d::Zero();\n\t\t\n double scale = -a/n2;\n axis = scale * axis;\n\n return axis;\n\n }\n\n // Utility functions\n double angleMod(double radians){\n return (double)(radians - (SM_2PI * boost::math::round(radians / SM_2PI)));\n }\n double deg2rad(double degrees){\n return (double)(degrees * SM_DEG2RAD);\n }\n double rad2deg(double radians){\n return (double)(radians * SM_RAD2DEG);\n }\n\n\n Eigen::Matrix3d Cx(double radians)\n {\n return Rx(-radians);\n }\n Eigen::Matrix3d Cy(double radians)\n {\n return Ry(-radians);\n }\n Eigen::Matrix3d Cz(double radians)\n {\n return Rz(-radians);\n }\n\n Eigen::Matrix3d rph2C(double x, double y, double z)\n { \n return rph2R(-x,-y,-z);\n }\n\n Eigen::Matrix3d rph2C(Eigen::Vector3d const & x)\n {\n return rph2C(x[0],x[1],x[2]);\n }\n Eigen::Matrix3d rph2C(Eigen::VectorXd const & x)\n {\n SM_ASSERT_EQ_DBG(std::runtime_error,x.size(),3,\"The input vector must have 3 components\");\n return rph2C(x[0],x[1],x[2]);\n }\n\n Eigen::Matrix3d rph2C(Eigen::MatrixXd const & A, unsigned column)\n {\n SM_ASSERT_EQ_DBG(std::runtime_error,A.rows(),3,\"The input matrix must have 3 rows\");\n SM_ASSERT_LT_DBG(std::runtime_error,column,A.cols(),\"The requested column is out of bounds\");\n return rph2C(A(0,column),A(1,column),A(2,column));\n }\n\n Eigen::Vector3d C2rph(Eigen::MatrixXd const & C)\n {\n SM_ASSERT_EQ_DBG(std::runtime_error,C.rows(),3,\"The input matrix must be 3x3\");\n SM_ASSERT_EQ_DBG(std::runtime_error,C.cols(),3,\"The input matrix must be 3x3\");\n\n Eigen::Vector3d rph;\n\n rph[1] = asin(C(2,0));\n rph[2] = atan2(-C(1,0),C(0,0));\n rph[0] = atan2(-C(2,1),C(2,2));\n\n return rph;\n }\n\n Eigen::Vector3d C2rph(Eigen::Matrix3d const & C)\n {\n Eigen::Vector3d rph;\n\n rph[1] = asin(C(2,0));\n rph[2] = atan2(-C(1,0),C(0,0));\n rph[0] = atan2(-C(2,1),C(2,2));\n\n return rph;\n }\n\n\n\n }} // sm::kinematics\n\n\n", "meta": {"hexsha": "603350d2c0e3a97dd91beff74021faf646cfa458", "size": 7137, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/sm_kinematics/src/rotations.cpp", "max_stars_repo_name": "PushyamiKaveti/kalibr", "max_stars_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 2690.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T03:50:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T20:27:01.000Z", "max_issues_repo_path": "Schweizer-Messer/sm_kinematics/src/rotations.cpp", "max_issues_repo_name": "PushyamiKaveti/kalibr", "max_issues_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 481.0, "max_issues_repo_issues_event_min_datetime": "2015-01-27T10:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:02:41.000Z", "max_forks_repo_path": "Schweizer-Messer/sm_kinematics/src/rotations.cpp", "max_forks_repo_name": "PushyamiKaveti/kalibr", "max_forks_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 1091.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T21:21:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T01:55:33.000Z", "avg_line_length": 30.2415254237, "max_line_length": 163, "alphanum_fraction": 0.5541544066, "num_tokens": 2857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.766778195098659}} {"text": "#include \n#include \n\nusing namespace std;\n\n#include \n#include \n\nusing namespace Eigen;\n\n// This program demonstrates how to use the Eigen geometry module\n\nint main(int argc, char **argv) {\n\n // The Eigen/Geometry module provides a variety of rotation and translation representations\n // 3D rotation matrix directly using Matrix3d or Matrix3f\n Matrix3d rotation_matrix = Matrix3d::Identity();\n // The rotation vector uses AngleAxis, the underlying layer is not directly Matrix,\n // but the operation can be treated as a matrix (because the operator is overloaded)\n AngleAxisd rotation_vector(M_PI / 4, Vector3d(0, 0, 1)); // Rotate 45 degrees along the Z axis\n cout.precision(3);\n cout << \"rotation matrix =\\n\" << rotation_vector.matrix() << endl; // convert to matrix with matrix()\n // can also be assigned directly\n rotation_matrix = rotation_vector.toRotationMatrix();\n // coordinate transformation with AngleAxis\n Vector3d v(1, 0, 0);\n Vector3d v_rotated = rotation_vector * v;\n cout << \"(1,0,0) after rotation (by angle axis) = \" << v_rotated.transpose() << endl;\n // Or use a rotation matrix\n v_rotated = rotation_matrix * v;\n cout << \"(1,0,0) after rotation (by matrix) = \" << v_rotated.transpose() << endl;\n\n // Euler angle: You can convert the rotation matrix directly into Euler angles\n Vector3d euler_angles = rotation_matrix.eulerAngles(2, 1, 0); // ZYX order, ie roll pitch yaw order\n cout << \"yaw pitch roll = \" << euler_angles.transpose() << endl;\n\n // Euclidean transformation matrix using Eigen::Isometry\n Isometry3d T = Isometry3d::Identity(); // Although called 3d, it is essentially a 4∗4 matrix\n T.rotate(rotation_vector); // Rotate according to rotation_vector\n T.pretranslate(Vector3d(1, 3, 4)); // Set the translation vector to (1,3,4)\n cout << \"Transform matrix = \\n\" << T.matrix() << endl;\n\n // Use the transformation matrix for coordinate transformation\n Vector3d v_transformed = T * v; // Equivalent to R∗v+t\n cout << \"v tranformed = \" << v_transformed.transpose() << endl;\n\n // For affine and projective transformations, use Eigen::Affine3d and Eigen::Projective3d.\n\n // Quaternion\n // You can assign AngleAxis directly to quaternions, and vice versa\n Quaterniond q = Quaterniond(rotation_vector);\n cout << \"quaternion from rotation vector = \" << q.coeffs().transpose()\n << endl; // Note that the order of coeffs is (x, y, z, w), w is the real part, the first three are the imaginary part\n // can also assign a rotation matrix to it\n q = Quaterniond(rotation_matrix);\n cout << \"quaternion from rotation matrix = \" << q.coeffs().transpose() << endl;\n // Rotate a vector with a quaternion and use overloaded multiplication\n v_rotated = q * v; // Note that the math is qvq^{−1}\n cout << \"(1,0,0) after rotation = \" << v_rotated.transpose() << endl;\n // expressed by regular vector multiplication, it should be calculated as follows\n cout << \"should be equal to \" << (q * Quaterniond(0, 1, 0, 0) * q.inverse()).coeffs().transpose() << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "402260e8da3ab997139f27866e34730ef88a50e1", "size": 3088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/useGeometry/eigenGeometry.cpp", "max_stars_repo_name": "SNU-SF4/slambook2", "max_stars_repo_head_hexsha": "eba0c28882fb6c78a9c81644f01fe93a80f83c7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch3/useGeometry/eigenGeometry.cpp", "max_issues_repo_name": "SNU-SF4/slambook2", "max_issues_repo_head_hexsha": "eba0c28882fb6c78a9c81644f01fe93a80f83c7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch3/useGeometry/eigenGeometry.cpp", "max_forks_repo_name": "SNU-SF4/slambook2", "max_forks_repo_head_hexsha": "eba0c28882fb6c78a9c81644f01fe93a80f83c7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.5076923077, "max_line_length": 124, "alphanum_fraction": 0.7027202073, "num_tokens": 805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7666621692405553}} {"text": "#include \n#include \nusing namespace std;\n\n#include \n// Eigen Geometry module\n#include \n\n/****************************\n* This program demonstrates how to use Eigen geometry module\n****************************/\n\nint main ( int argc, char** argv )\n{\n // Eigen/Geometry The module provides various representations of rotation and translation\n // 3D rotation matrix directly use Matrix3d or Matrix3f\n Eigen::Matrix3d rotation_matrix = Eigen::Matrix3d::Identity();\n // Rotation vector uses AngleAxis, its underlying layer is not directly Matrix, \n // but the operation can be treated as a matrix (because the operator is overloaded)\n //Rotate 45 degrees along the Z axis\n Eigen::AngleAxisd rotation_vector ( M_PI/4, Eigen::Vector3d ( 0,0,1 ) ); \n cout .precision(3);\n //Use matrix() to convert to a matrix\n cout<<\"rotation matrix =\\n\"<\n#include \n#include \n#include \"common.h\"\n\nusing arma::mat;\nusing arma::svd;\nusing arma::vec;\nusing std::vector;\n\nmat calculate_pseudoinverse(mat x)\n{\n return x.t() * inv(x * x.t());\n}\n\nmat calculate_sum_signal(mat weigths, mat signals)\n{\n return weigths * signals;\n}\n\nmat calculate_svd_inverse(mat x, int rank)\n{\n // If rank = -1, use full rank (= smaller dimension of matrix x)\n if (rank == -1)\n {\n rank = std::min(x.n_cols, x.n_rows);\n }\n\n mat u, v;\n vec s;\n svd(u, s, v, x);\n mat s_inv = 1 / s;\n\n int lb = s_inv.n_elem - rank;\n int ub = s_inv.n_elem - 1;\n\n s_inv = s_inv.rows(lb, ub);\n v = v.cols(lb, ub);\n u = u.cols(lb, ub);\n mat sigma_inv = diagmat(s_inv);\n\n return v * sigma_inv * u.t();\n}\n\nmat low_rank_approximation(mat x, int rank)\n{\n mat u, v;\n vec s;\n svd(u, s, v, x);\n\n s = s.rows(0, rank - 1);\n v = v.cols(0, rank - 1);\n u = u.cols(0, rank - 1);\n\n return u * diagmat(s) * v.t();\n}\n\narma::mat trimmed_mean(arma::vec x, int n_points)\n{\n int lb = n_points;\n int ub = x.n_elem - n_points - 1;\n arma::vec x_sorted = arma::sort(x, \"ascend\");\n return arma::mean(x_sorted.rows(lb, ub), 0);\n}\n\narma::mat trimmed_mean(arma::vec x, float proportion)\n{\n int n_points = round(proportion * x.n_elem);\n return trimmed_mean(x, n_points);\n}\n\narma::mat rmse(arma::mat estimate_values, arma::mat true_values)\n{\n arma::mat difference = estimate_values - true_values;\n return sqrt(sum(pow(difference, 2), 1) / difference.n_elem);\n}\n\narma::mat mae(arma::mat estimate_values, arma::mat true_values)\n{\n arma::mat difference = estimate_values - true_values;\n return arma::sum(arma::abs(difference), 1) / difference.n_elem;\n}\n\narma::mat trimmed_mae(arma::vec estimate_values, arma::vec true_values, double rejection_threshold)\n{\n arma::vec difference = estimate_values - true_values;\n arma::vec abs_difference = arma::abs(difference);\n int n_points = round(rejection_threshold * abs_difference.n_elem);\n arma::vec abs_difference_sorted = arma::sort(abs_difference, \"descent\");\n return arma::mean(abs_difference_sorted.rows(n_points, abs_difference_sorted.n_elem - 1), 0);\n}\n\nstd::vector sample_without_replacement(int lb, int ub, int n)\n{\n std::vector vec;\n for (size_t i = lb; i <= ub; i++)\n {\n vec.push_back(i);\n }\n std::random_device device;\n std::mt19937 generator(device());\n std::shuffle(vec.begin(), vec.end(), generator);\n std::vector out(vec.begin(), vec.begin() + n);\n return out;\n}", "meta": {"hexsha": "d9e012031a9cf7eed17f4eb7264e6a22e836551a", "size": 2591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/common.cpp", "max_stars_repo_name": "omyllymaki/math", "max_stars_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-11-04T03:43:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T09:12:24.000Z", "max_issues_repo_path": "src/common.cpp", "max_issues_repo_name": "omyllymaki/math", "max_issues_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common.cpp", "max_forks_repo_name": "omyllymaki/math", "max_forks_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6761904762, "max_line_length": 99, "alphanum_fraction": 0.6383635662, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7663607399893259}} {"text": "#include \n#include \n#include \n#include \n#include \"sophus/se3.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\n\n/// This program demonstrates the basic usage of Sophus\n\nint main(int argc, char **argv) {\n\n // Rotation matrix with 90 degrees along Z axis\n Matrix3d R = AngleAxisd(M_PI / 2, Vector3d(0, 0, 1)).toRotationMatrix();\n // or quaternion\n Quaterniond q(R);\n Sophus::SO3d SO3_R(R); // Sophus::SO3d can be constructed from rotation matrix\n Sophus::SO3d SO3_q(q); // or quaternion\n // they are equivalent of course\n cout << \"SO(3) from matrix:\\n\" << SO3_R.matrix() << endl;\n cout << \"SO(3) from quaternion:\\n\" << SO3_q.matrix() << endl;\n cout << \"they are equal\" << endl;\n\n // Use logarithmic map to get the Lie algebra\n Vector3d so3 = SO3_R.log();\n cout << \"so3 = \" << so3.transpose() << endl;\n // hat is from vector to skew−symmetric matrix\n cout << \"so3 hat=\\n\" << Sophus::SO3d::hat(so3) << endl;\n // inversely from matrix to vector\n cout << \"so3 hat vee= \" << Sophus::SO3d::vee(Sophus::SO3d::hat(so3)).transpose() << endl;\n\n // update by perturbation model\n Vector3d update_so3(1e-4, 0, 0); // this is a small update\n Sophus::SO3d SO3_updated = Sophus::SO3d::exp(update_so3) * SO3_R;\n cout << \"SO3 updated = \\n\" << SO3_updated.matrix() << endl;\n\n cout << \"*******************************\" << endl;\n // Similar for SE(3)\n Vector3d t(1, 0, 0); // translation 1 along X\n Sophus::SE3d SE3_Rt(R, t); // construction SE3 from R,t\n Sophus::SE3d SE3_qt(q, t); // or q,t\n cout << \"SE3 from R,t= \\n\" << SE3_Rt.matrix() << endl;\n cout << \"SE3 from q,t= \\n\" << SE3_qt.matrix() << endl;\n // Lie Algebra is 6d vector, we give a typedef\n typedef Eigen::Matrix Vector6d;\n Vector6d se3 = SE3_Rt.log();\n cout << \"se3 = \" << se3.transpose() << endl;\n // The output shows Sophus puts the translation at first in se(3), then rotation.\n // Save as SO(3) wehave hat and vee\n cout << \"se3 hat = \\n\" << Sophus::SE3d::hat(se3) << endl;\n cout << \"se3 hat vee = \" << Sophus::SE3d::vee(Sophus::SE3d::hat(se3)).transpose() << endl;\n\n // Finally the update\n Vector6d update_se3;\n update_se3.setZero();\n update_se3(0, 0) = 1e-4;\n Sophus::SE3d SE3_updated = Sophus::SE3d::exp(update_se3) * SE3_Rt;\n cout << \"SE3 updated = \" << endl << SE3_updated.matrix() << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "155191b0970d55343c1f5224db618d2ae3f2ba9b", "size": 2400, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch4/useSophus.cpp", "max_stars_repo_name": "SNU-SF4/slambook2", "max_stars_repo_head_hexsha": "eba0c28882fb6c78a9c81644f01fe93a80f83c7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch4/useSophus.cpp", "max_issues_repo_name": "SNU-SF4/slambook2", "max_issues_repo_head_hexsha": "eba0c28882fb6c78a9c81644f01fe93a80f83c7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch4/useSophus.cpp", "max_forks_repo_name": "SNU-SF4/slambook2", "max_forks_repo_head_hexsha": "eba0c28882fb6c78a9c81644f01fe93a80f83c7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0952380952, "max_line_length": 93, "alphanum_fraction": 0.6225, "num_tokens": 809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7662882326181826}} {"text": "#include \n#include \n#include \n\ntemplate \nvoid dampnewton(const FuncType &F, const JacType &DF,\n Eigen::VectorXd &x, double rtol = 1e-4,double atol = 1e-6)\n{\n const int n = x.size();\n const double lmin = 1E-3; // Minimal damping factor\n double lambda = 1.0; // Initial and actual damping factor\n Eigen::VectorXd s(n),st(n); // Newton corrections\n Eigen::VectorXd xn(n); // Tentative new iterate\n double sn,stn; // Norms of Newton corrections\n \n do {\n auto jacfac = DF(x).lu(); // LU-factorize Jacobian\n \n s = jacfac.solve(F(x)); // Newton correction\n sn = s.norm(); // Norm of Newton correction\n lambda *= 2.0;\n do {\n lambda /= 2;\n if (lambda < lmin) throw \"No convergence: lambda -> 0\";\n xn = x-lambda*s; // {\\bf Tentative next iterate}\n st = jacfac.solve(F(xn)); // Simplified Newton correction\n stn = st.norm();\n }\n while (stn > (1-lambda/2)*sn); // {\\bf Natural monotonicity test}\n x = xn; // Now: xn accepted as new iterate\n lambda = std::min(2.0*lambda,1.0); // Try to mitigate damping\n }\n // Termination based on simplified Newton correction\n while ((stn > rtol*x.norm()) && (stn > atol));\n}", "meta": {"hexsha": "d4e8bf26faa337eef20ed3e4c324c492c1515df6", "size": 1370, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS14/solutions_ps14/dampnewton.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/PS14/templates_ps14/dampnewton.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/PS14/templates_ps14/dampnewton.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.1428571429, "max_line_length": 74, "alphanum_fraction": 0.5686131387, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.766247899953821}} {"text": "#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n\nnamespace pcv\n{\n\ntemplate\ndouble getReprojectionError(\n const Eigen::Matrix3d &model,\n const std::pair, cv::Point_>\n &correspondence)\n{\n static_assert(std::is_arithmetic::value,\n \"Must have a numerical point type.\");\n\n // Make the first correspondence a homogenous-coordinate column vector.\n Eigen::Vector3d homogenousFirst;\n homogenousFirst <<\n correspondence.first.x,\n correspondence.first.y,\n 1.0;\n\n Eigen::Vector3d estimate = model * homogenousFirst;\n estimate /= estimate(2);\n\n return std::sqrt( std::pow(estimate(0)-correspondence.second.x, 2)\n + std::pow(estimate(1)-correspondence.second.y, 2));\n}\n\ntemplate\nEigen::Matrix3d\nfindHomographyWithLeastSquares(\n std::vector, cv::Point_ >>\n correspondences)\n{\n static_assert(std::is_arithmetic::value,\n \"Must have a numerical point type.\");\n\n // Allocate appropriate amount of memory for Matrix.\n Eigen::MatrixXd joinedPoints(2*correspondences.size(), 9);\n\n for (std::size_t correspondenceIndex = 0; correspondenceIndex < correspondences.size(); ++correspondenceIndex)\n {\n const auto &pointPair = correspondences[correspondenceIndex];\n\n joinedPoints.row(2*correspondenceIndex) <<\n -pointPair.first.x,\n -pointPair.first.y,\n -1,\n 0,\n 0,\n 0,\n pointPair.first.x*pointPair.second.x,\n pointPair.first.y*pointPair.second.x,\n pointPair.second.x;\n\n joinedPoints.row(2*correspondenceIndex+1) <<\n 0,\n 0,\n 0,\n -pointPair.first.x,\n -pointPair.first.y,\n -1,\n pointPair.first.x*pointPair.second.y,\n pointPair.first.y*pointPair.second.y,\n pointPair.second.y;\n }\n\n Eigen::JacobiSVD svd(\n joinedPoints.transpose()*joinedPoints, Eigen::ComputeFullV);\n\n auto output =\n Eigen::Matrix(svd.matrixV().col(8).data());\n\n return output / output(2, 2);\n}\n\ntemplate\nEigen::Matrix3d\nfindHomographyWithDirectLinearTransform(\n std::vector, cv::Point_ >>\n correspondences)\n{\n static_assert(std::is_arithmetic::value,\n \"Must have a numerical point type.\");\n\n Eigen::Matrix joinedPoints;\n\n std::array, 4> points;\n\n std::transform(\n std::cbegin(correspondences),\n std::cend(correspondences),\n std::begin(points),\n [](std::pair pointPair)\n {\n Eigen::Matrix tmp;\n tmp <<\n -pointPair.first.x,\n -pointPair.first.y, -1, 0,\n 0,\n 0,\n pointPair.first.x*pointPair.second.x,\n pointPair.first.y*pointPair.second.x,\n pointPair.second.x,\n 0,\n 0,\n 0,\n -pointPair.first.x,\n -pointPair.first.y,\n -1,\n pointPair.first.x*pointPair.second.y,\n pointPair.first.y*pointPair.second.y,\n pointPair.second.y;\n\n return tmp;\n });\n\n joinedPoints << points[0], points[1], points[2], points[3];\n\n Eigen::JacobiSVD svd(joinedPoints, Eigen::ComputeFullV);\n\n auto output =\n Eigen::Matrix(svd.matrixV().col(8).data());\n\n return output / output(2, 2);\n}\n\n} // end namespace pcv\n", "meta": {"hexsha": "6986f3cfdfb6ebf9bf0b7aa64e1646f1131d3d16", "size": 3993, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/Solvers/include/Solvers/Image.hpp", "max_stars_repo_name": "Pratool/homography", "max_stars_repo_head_hexsha": "c9daeaa3364b7c658b39c225952288dd828c332e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-12T17:38:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-12T17:38:22.000Z", "max_issues_repo_path": "cpp/Solvers/include/Solvers/Image.hpp", "max_issues_repo_name": "Pratool/homography", "max_issues_repo_head_hexsha": "c9daeaa3364b7c658b39c225952288dd828c332e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-03-03T15:43:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-04T03:22:47.000Z", "max_forks_repo_path": "cpp/Solvers/include/Solvers/Image.hpp", "max_forks_repo_name": "Pratool/homography", "max_forks_repo_head_hexsha": "c9daeaa3364b7c658b39c225952288dd828c332e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5214285714, "max_line_length": 114, "alphanum_fraction": 0.59103431, "num_tokens": 970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7662396197813868}} {"text": "#include \n\n//#define USING_MLOGD\n#include \"utility/tool.h\"\n#include \n//#include // Eigen 几何模块\n\n\n/**\n * @brief 使用Gramy-Schmidt方法实现向量正交化,并单位化\n * @param [in] a 向量a\n * @param [in] b 向量b\n * @param [in] c 向量c\n * @param [out] An 标准化后的向量A\n * @param [out] Bn 标准化后的向量B\n * @param [out] Cn 标准化后的向量C\n * @retval\n * @note a,b,c必须为线性无关组\n */\nstatic void schmidtOrthogonalV3D(\n Eigen::Vector3d a,\n Eigen::Vector3d b,\n Eigen::Vector3d c,\n Eigen::Vector3d* An,\n Eigen::Vector3d* Bn,\n Eigen::Vector3d* Cn ){\n\n Eigen::Vector3d A,B,C;\n //A直接赋值为a\n A = a;\n //MLOGD(\"vector A: %.3lf %.3f %.3f\", A.x(), A.y(), A.z() );\n //求B\n double xab = A.dot(b) / A.dot( A );\n B = b - xab * A;\n //MLOGD(\"vector B: %.3lf %.3f %.3f\", B.x(), B.y(), B.z() );\n //求C\n double xac = A.dot( c ) / A.dot( A );\n double xbc = B.dot( c ) / B.dot( B );\n C = c - ( xac * A ) - ( xbc * B );\n //MLOGD(\"vector C: %.3lf %.3f %.3f\", C.x(), C.y(), C.z() );\n //单位化并输出\n *An = A.normalized();\n *Bn = B.normalized();\n *Cn = C.normalized();\n //MLOGD(\"normalized vector A: %.3lf %.3f %.3f\", An->x(), An->y(), An->z() );\n //MLOGD(\"normalized vector B: %.3lf %.3f %.3f\", Bn->x(), Bn->y(), Bn->z() );\n //MLOGD(\"normalized vector C: %.3lf %.3f %.3f\", Cn->x(), Cn->y(), Cn->z() );\n}\n\n\n//--------------------测试函数----------------------------\nstatic void schmidtOrthogonalTest( void ) {\n //线性无关组1\n Eigen::Vector3d a(1,1.2,0);\n Eigen::Vector3d b(1,2,0);\n Eigen::Vector3d c(0,1,1);\n\n //线性无关组2\n Eigen::Vector3d v1(9,1.2,2.4);\n Eigen::Vector3d v2(1,2,6.7);\n Eigen::Vector3d v3(5,1.5,1);\n\n Eigen::Vector3d A,B,C;\n\n schmidtOrthogonalV3D( a, b, c, &A, &B, &C );\n //schmidtOrthogonalV3D( v1, v2, v3, &A, &B, &C );\n TPLOGI(\"normalized vector A: %.3lf %.3f %.3f\", A.x(), A.y(), A.z() );\n TPLOGI(\"normalized vector B: %.3lf %.3f %.3f\", B.x(), B.y(), B.z() );\n TPLOGI(\"normalized vector C: %.3lf %.3f %.3f\", C.x(), C.y(), C.z() );\n}\n\n", "meta": {"hexsha": "caf9506bec8989b42c3c560844f90f1c57e823e2", "size": 2178, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "schmidt.hpp", "max_stars_repo_name": "deakinYellow/utility-math", "max_stars_repo_head_hexsha": "7b465ca7031fe85579c13d81732d8b20bbbf1acb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "schmidt.hpp", "max_issues_repo_name": "deakinYellow/utility-math", "max_issues_repo_head_hexsha": "7b465ca7031fe85579c13d81732d8b20bbbf1acb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "schmidt.hpp", "max_forks_repo_name": "deakinYellow/utility-math", "max_forks_repo_head_hexsha": "7b465ca7031fe85579c13d81732d8b20bbbf1acb", "max_forks_repo_licenses": ["Apache-2.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.25, "max_line_length": 80, "alphanum_fraction": 0.4724517906, "num_tokens": 874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104865, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7662396164003328}} {"text": "#include \r\n#include \r\n\r\nusing namespace Eigen;\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n MatrixXd m = MatrixXd::Random(3,3);\r\n m = (m + MatrixXd::Constant(3,3,1.2)) * 50;\r\n cout << \"m =\" << endl << m << endl;\r\n VectorXd v(3);\r\n v << 1, 2, 3;\r\n cout << \"m * v =\" << endl << m * v << endl;\r\n}\r\n", "meta": {"hexsha": "c8b1cd4a8376be0e5163b944a664d70204681946", "size": 320, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/QuickStart_example2_dynamic.cpp", "max_stars_repo_name": "k4rth33k/dnnc-operators", "max_stars_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T14:35:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-11T23:59:22.000Z", "max_issues_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/QuickStart_example2_dynamic.cpp", "max_issues_repo_name": "k4rth33k/dnnc-operators", "max_issues_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-08-12T04:38:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T16:32:13.000Z", "max_forks_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/QuickStart_example2_dynamic.cpp", "max_forks_repo_name": "k4rth33k/dnnc-operators", "max_forks_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-08-15T13:29:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-09T17:08:04.000Z", "avg_line_length": 20.0, "max_line_length": 46, "alphanum_fraction": 0.525, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525463, "lm_q2_score": 0.8397339676722394, "lm_q1q2_score": 0.7662036292869681}} {"text": "#include \n#include \nusing namespace arma;\nint main() \n{\n // arma::mat A(5, 5, arma::fill::randu);\n // arma::mat B(5, 5, arma::fill::randn);\n // std::cout << A * B << std::endl;\n mat X = randu(5,5);\n mat Y = X.t()*X;\n mat R1 = chol(Y);\n std::cout << R1 << std::endl;\n}\n", "meta": {"hexsha": "7cae6075347882951c820d3544897e129544d605", "size": 315, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/armadillo/foo.cpp", "max_stars_repo_name": "PhoebeWangintw/hunter", "max_stars_repo_head_hexsha": "67fadbe7388254c8626b2130c0afb0a5f1817e47", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-28T06:24:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T17:10:35.000Z", "max_issues_repo_path": "examples/armadillo/foo.cpp", "max_issues_repo_name": "PhoebeWangintw/hunter", "max_issues_repo_head_hexsha": "67fadbe7388254c8626b2130c0afb0a5f1817e47", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/armadillo/foo.cpp", "max_forks_repo_name": "PhoebeWangintw/hunter", "max_forks_repo_head_hexsha": "67fadbe7388254c8626b2130c0afb0a5f1817e47", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-02T16:07:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-02T16:07:55.000Z", "avg_line_length": 22.5, "max_line_length": 44, "alphanum_fraction": 0.5238095238, "num_tokens": 114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9597620539235896, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7660693904330831}} {"text": "/*\n * main.cpp\n *\n * Created on: 2021/07/22\n * Author: matsu\n */\n#include \n#include \n#include \n#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\nvoid test_intro1();\nvoid test_intro2_1();\nvoid test_intro2_2();\n\n\nint main( int argc, char** argv )\n{\n vector< string > args( argv, argv + argc );\n\n if ( args.at( 1 ) == string( \"intro1\" ) )\n {\n test_intro1();\n }\n else if ( args.at( 1 ) == string( \"intro2_1\" ) )\n {\n test_intro2_1();\n }\n else if ( args.at( 1 ) == string( \"intro2_2\" ) )\n {\n test_intro2_2();\n }\n else\n {\n fprintf( stderr, \"Matching test is not exist.\\n\" );\n exit( -1 );\n }\n\n return 0;\n}\n\nvoid test_intro1()\n{\n MatrixXd m( 2, 2 );\n m( 0, 0 ) = 3;\n m( 1, 0 ) = 2.5;\n m( 0, 1 ) = -1;\n m( 1, 1 ) = m( 1, 0 ) + m( 0, 1 );\n std::cout << m << std::endl;\n}\n\nvoid test_intro2_1()\n{\n MatrixXd m = MatrixXd::Random( 3, 3 );\n m = ( m + MatrixXd::Constant( 3, 3, 1.2 ) ) * 50;\n cout << \"m =\" << endl\n << m << endl;\n VectorXd v( 3 );\n v << 1, 2, 3;\n cout << \"m * v =\" << endl\n << m * v << endl;\n}\n\nvoid test_intro2_2()\n{\n Matrix3d m = Matrix3d::Random();\n m = ( m + Matrix3d::Constant( 1.2 ) ) * 50;\n cout << \"m =\" << endl\n << m << endl;\n Vector3d v( 1, 2, 3 );\n\n cout << \"m * v =\" << endl\n << m * v << endl;\n}", "meta": {"hexsha": "617e578904c506f4e3fce0c5678813d17866bfba", "size": 1436, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/available_with_eigen/with_eigen.cpp", "max_stars_repo_name": "dsp-work/sound_utils", "max_stars_repo_head_hexsha": "58cb06375422b5f5777b5341e6a8fe08b7aeff7c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/available_with_eigen/with_eigen.cpp", "max_issues_repo_name": "dsp-work/sound_utils", "max_issues_repo_head_hexsha": "58cb06375422b5f5777b5341e6a8fe08b7aeff7c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2021-11-25T01:44:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-25T03:42:00.000Z", "max_forks_repo_path": "test/available_with_eigen/with_eigen.cpp", "max_forks_repo_name": "dsp-work/sound_utils", "max_forks_repo_head_hexsha": "58cb06375422b5f5777b5341e6a8fe08b7aeff7c", "max_forks_repo_licenses": ["Apache-2.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.4102564103, "max_line_length": 59, "alphanum_fraction": 0.4749303621, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7656763422091497}} {"text": "#include \n#include \n\nusing namespace std;\nusing namespace Eigen;\n\nvoid rankoneinvit(const VectorXd & d, const double & tol, double & lmin) {\n\tMatrixXd M;\n\tVectorXd ev = d;\n\tlmin = 0.;\n\tdouble lnew = d.cwiseAbs().minCoeff();\n\twhile (abs(lnew-lmin) > tol*lmin){\n\t\tlmin = lnew;\n\t\tM = d.asDiagonal(); M+=ev*ev.transpose();\n\t\tev = M.lu().solve(ev);\n\t\tev.normalize();\n\t\tlnew = ev.transpose()*M* ev;\n\t\t}\n\tlmin=lnew;\n}\n\n\nint main(){\n double tol=1e-3;\n double lmin;\n int n=10;\n \n VectorXd d=VectorXd::Random(n);\n rankoneinvit(d,tol,lmin);\n cout<<\"lmin = \"<\n#include \n#include \"timer.h\"\n\nvoid rankoneinvit(const Eigen::VectorXd & d, const double & tol, double & lmin){\n\tlmin=0.;\n\tEigen::VectorXd ev;\n\tint n=d.size();\n\tEigen::MatrixXd M;\n\tev=d;\n\tdouble lnew = d.cwiseAbs().minCoeff();\n\twhile(std::abs(lnew-lmin)> tol*lmin){\n\t\tlmin=lnew;\n\t\tM=d.asDiagonal();\n\t\tM+=ev*ev.transpose();\n\t\tev= M.partialPivLu().solve(ev);\n\t\tev.normalize();\n\t\tlnew= ev.transpose()*M*ev;\n\t}\n\tlmin=lnew;\n} \n\n\nusing namespace std;\nusing namespace Eigen;\nint main(){\n srand((unsigned int) time(0));\n double tol=1e-3;\n double lmin;\n int n=10;\n \n // Check correctedness of the fast version\n VectorXd d=VectorXd::Random(n);\n rankoneinvit(d,tol,lmin);\n cout<<\"lmin = \"<\r\n * @brief \r\n * @version 0.1\r\n * @date 2018-11-08\r\n * \r\n * @copyright Copyright (c) 2018\r\n * \r\n */\r\n#pragma once\r\n\r\n#include \"various.hpp\"\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace Eigen;\r\nusing namespace std;\r\nusing namespace ranges;\r\n\r\n\r\ntemplate\r\nVectorXd pls(const MatrixBase& x,\r\n const MatrixBase& y,\r\n size_t ncomp,\r\n MatrixXd& Projection,\r\n RowVectorXd& mean,\r\n RowVectorXd& std,\r\n bool stopping = false)\r\n{\r\n auto n = x.rows();\r\n auto p = x.cols();\r\n mean = x.colwise().mean();\r\n std = ((x.rowwise() - mean).array().square().colwise().sum() / (x.rows() - 1)).sqrt();;\r\n MatrixXd X = (x.rowwise() - mean).array().rowwise() / std.array();\r\n MatrixXd Xo = X;\r\n MatrixXd XX = X.transpose() * X;\r\n MatrixXd Y = MatrixXd::Zero(n, ncomp + 1);\r\n MatrixXd P(p,ncomp);\r\n MatrixXd R(p,ncomp);\r\n VectorXd XY(n); \r\n VectorXd w(p);\r\n VectorXd r(p);\r\n VectorXd t(p);\r\n VectorXd res(ncomp);\r\n size_t window_size = std::max(2_z,ncomp/10_z);\r\n\r\n std::list stopping_criterium(window_size,0);\r\n // Y.col(0) = y.rowwise() - y.colwise().mean();\r\n double ymean = y.mean();\r\n Y.col(0).array() = ymean;\r\n double SSTO = (y.array() - ymean).array().square().sum();\r\n int m = 0;\r\n // for (auto m = 0; m < ncomp; m++)\r\n while (m < ncomp)\r\n {\r\n XY = X.transpose() * y;\r\n SelfAdjointEigenSolver es( XY.transpose() * XY );\r\n auto abs_eigenvalues = es.eigenvalues().array().abs();\r\n size_t max_eigenvalue_indice = ranges::distance(abs_eigenvalues.begin(),ranges::max_element(abs_eigenvalues));\r\n auto q = es.eigenvectors().col(max_eigenvalue_indice);\r\n w = XY * q;\r\n w /= sqrt((w.transpose()*w)(0,0));\r\n r=w;\r\n for (auto j=0; j<=m-1;j++)\r\n {\r\n r -= (P.col(j).transpose()*w)(0,0)*R.col(j);\r\n }\r\n R.col(m) = r;\r\n t = Xo * r;\r\n P.col(m) = XX *r/(t.transpose()*t)(0,0);\r\n VectorXd Zm = X * XY;\r\n double Znorm = Zm.array().square().sum();\r\n double Thetam = Zm.dot(y) / Znorm;\r\n Y.col(m + 1) = Y.col(m) + Thetam * Zm;\r\n X -= Zm.rowwise().replicate(p) * ((Zm/Znorm).transpose() * X).asDiagonal();\r\n res(m) = (Y.col(m + 1).array() - ymean).array().square().sum() / SSTO;\r\n if ((m >= 2) && stopping) {\r\n auto lastdiff = res(m) - res(m-1);\r\n auto lastmean = (res(m) + res(m-1))/2.0;\r\n size_t remains = ncomp - m;\r\n stopping_criterium.pop_front();\r\n stopping_criterium.push_back(lastmean >= 0.99 * remains * lastdiff);\r\n auto wcrit = ranges::accumulate(stopping_criterium,0);\r\n if (wcrit == window_size) break;\r\n }\r\n m++;\r\n }\r\n if (m < ncomp) {\r\n m--;\r\n res = res(seq(0,m)).eval();\r\n }\r\n Projection = R;\r\n// VectorXd res = (Y.block(0,1,n,ncomp).array() - ymean).array().square().colwise().sum() / SSTO;\r\n return res;\r\n}", "meta": {"hexsha": "a0361be2d6345532847b6d4913d79cb4dd72bf6e", "size": 3358, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pls-eigen.hpp", "max_stars_repo_name": "vitorpavinato/abcranger", "max_stars_repo_head_hexsha": "71f950817bedeebed12d13610d8747c6dcc75a72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-29T13:31:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-29T13:31:43.000Z", "max_issues_repo_path": "src/pls-eigen.hpp", "max_issues_repo_name": "vitorpavinato/abcranger", "max_issues_repo_head_hexsha": "71f950817bedeebed12d13610d8747c6dcc75a72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pls-eigen.hpp", "max_forks_repo_name": "vitorpavinato/abcranger", "max_forks_repo_head_hexsha": "71f950817bedeebed12d13610d8747c6dcc75a72", "max_forks_repo_licenses": ["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.9215686275, "max_line_length": 119, "alphanum_fraction": 0.5422870756, "num_tokens": 980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570318, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7654243672705896}} {"text": "#pragma once\n#include \"dirichlet_boundary.hpp\"\n#include \"load_vector_assembly.hpp\"\n#include \"stiffness_matrix_assembly.hpp\"\n#include \n#include \n#include \n#include \n#include \n\ntypedef Eigen::VectorXd Vector;\n\n//----------------solveBegin----------------\n//! Solve the FEM system.\n//!\n//! @param[out] u will at the end contain the FEM solution.\n//! @param[in] vertices list of triangle vertices for the mesh\n//! @param[in] triangles list of triangles (described by indices)\n//! @param[in] f the RHS f (as in the exercise)\n//! @param[in] g the boundary value (as in the exercise)\n//! @param[in] sigma the function sigma as in the exercise\n//! @param[in] r the parameter r from the lecture notes\n//! return number of degrees of freedom (without the boundary dofs)\nint solveFiniteElement(Vector & u,\n const Eigen::MatrixXd &vertices,\n const Eigen::MatrixXi &triangles,\n const std::function &f,\n const std::function &sigma,\n const std::function &g,\n double r) {\n\tSparseMatrix A;\n\t// (write your solution here)\n\tassembleStiffnessMatrix(A, vertices, triangles, sigma, r);\n\n\tVector F;\n\t// (write your solution here)\n\tassembleLoadVector(F, vertices, triangles, f);\n\n\tu.resize(vertices.rows());\n\tu.setZero();\n\tEigen::VectorXi interiorVertexIndices;\n\n\t// set Dirichlet Boundary conditions\n\t// (write your solution here)\n\tsetDirichletBoundary(u, interiorVertexIndices, vertices, triangles, g);\n\tF -= A * u;\n\n\tSparseMatrix AInterior;\n\n\tigl::slice(A, interiorVertexIndices, interiorVertexIndices, AInterior);\n\tEigen::SimplicialLDLT solver;\n\n\tVector FInterior;\n\n\tigl::slice(F, interiorVertexIndices, FInterior);\n\n\t//initialize solver for AInterior\n\t// (write your solution here)\n\t//// NPDE_START_TEMPLATE\n\tsolver.compute(AInterior);\n\n\tif (solver.info() != Eigen::Success) {\n\t\tthrow std::runtime_error(\"Could not decompose the matrix\");\n\t}\n\t//// NPDE_END_TEMPLATE\n\n\t//solve interior system\n\t// (write your solution here)\n\t//// NPDE_START_TEMPLATE\n\tVector uInterior = solver.solve(FInterior);\n\tigl::slice_into(uInterior, interiorVertexIndices, u);\n\t//// NPDE_END_TEMPLATE\n\n\treturn interiorVertexIndices.size();\n}\n//----------------solveEnd----------------\n", "meta": {"hexsha": "3aa01d589694579bb43c8fd3ceb2cb1503d4a479", "size": 2436, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series2/2d-linFEM/fem_solve.hpp", "max_stars_repo_name": "westernmagic/NumPDE", "max_stars_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "series2/2d-linFEM/fem_solve.hpp", "max_issues_repo_name": "westernmagic/NumPDE", "max_issues_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-04-01T22:52:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T16:21:55.000Z", "max_forks_repo_path": "series2/2d-linFEM/fem_solve.hpp", "max_forks_repo_name": "westernmagic/NumPDE", "max_forks_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6363636364, "max_line_length": 74, "alphanum_fraction": 0.6748768473, "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201267, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7653204736022824}} {"text": "#include \n#include \n#include \n\nusing Eigen::VectorXf;\nusing Eigen::MatrixXf;\nusing namespace LBFGSpp;\n\nclass Rosenbrock\n{\nprivate:\n int n;\npublic:\n Rosenbrock(int n_) : n(n_) {}\n float operator()(const VectorXf& x, VectorXf& grad)\n {\n float fx = 0.0;\n for(int i = 0; i < n; i += 2)\n {\n float t1 = 1.0 - x[i];\n float t2 = 10 * (x[i + 1] - x[i] * x[i]);\n grad[i + 1] = 20 * t2;\n grad[i] = -2.0 * (x[i] * grad[i + 1] + t1);\n fx += t1 * t1 + t2 * t2;\n }\n return fx;\n }\n};\n\nint main()\n{\n const int n = 10;\n LBFGSParam param;\n LBFGSSolver solver(param);\n Rosenbrock fun(n);\n\n VectorXf x = VectorXf::Zero(n);\n float fx;\n int niter = solver.minimize(fun, x, fx);\n\n std::cout << niter << \" iterations\" << std::endl;\n std::cout << \"x = \\n\" << x.transpose() << std::endl;\n std::cout << \"f(x) = \" << fx << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "b83a6c956c3fa49cb2cd9e727b5b15fc5d70cb08", "size": 1006, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/lbfgs/example-rosenbrock.cpp", "max_stars_repo_name": "hcyang99/horovod", "max_stars_repo_head_hexsha": "825cc197468548da47dcd38872d5b4ba6e6a125b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-08-05T06:18:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T06:30:01.000Z", "max_issues_repo_path": "third_party/lbfgs/example-rosenbrock.cpp", "max_issues_repo_name": "hcyang99/horovod", "max_issues_repo_head_hexsha": "825cc197468548da47dcd38872d5b4ba6e6a125b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2017-06-24T18:51:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T04:42:49.000Z", "max_forks_repo_path": "third_party/lbfgs/example-rosenbrock.cpp", "max_forks_repo_name": "hcyang99/horovod", "max_forks_repo_head_hexsha": "825cc197468548da47dcd38872d5b4ba6e6a125b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 82.0, "max_forks_repo_forks_event_min_datetime": "2016-08-26T22:11:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T16:25:55.000Z", "avg_line_length": 21.4042553191, "max_line_length": 59, "alphanum_fraction": 0.4960238569, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776495, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7653136999811344}} {"text": "// https://stackoverflow.com/questions/21412169/creating-a-rotation-matrix-with-pitch-yaw-roll-using-eigen\n#include \n#include \n#include \n\nEigen::Matrix3d rotation_from_euler(double roll, double pitch, double yaw)\n{\n // roll and pitch and yaw in radians\n double su = sin(roll);\n double cu = cos(roll);\n double sv = sin(pitch);\n double cv = cos(pitch);\n double sw = sin(yaw);\n double cw = cos(yaw);\n Eigen::Matrix3d Rot_matrix(3, 3);\n Rot_matrix(0, 0) = cv * cw;\n Rot_matrix(0, 1) = su * sv * cw - cu * sw;\n Rot_matrix(0, 2) = su * sw + cu * sv * cw;\n Rot_matrix(1, 0) = cv * sw;\n Rot_matrix(1, 1) = cu * cw + su * sv * sw;\n Rot_matrix(1, 2) = cu * sv * sw - su * cw;\n Rot_matrix(2, 0) = -sv;\n Rot_matrix(2, 1) = su * cv;\n Rot_matrix(2, 2) = cu * cv;\n return Rot_matrix;\n}\n\nint main()\n{\n Eigen::Matrix3d rot_mat = rotation_from_euler(0, 0, 0.5 * M_PI);\n std::cout << rot_mat << std::endl;\n return 0;\n}\n", "meta": {"hexsha": "2b77c7487f47970750b1b5569fde1ff136d69c49", "size": 994, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rotation_from_euler.cpp", "max_stars_repo_name": "yubaoliu/VisualizeGeometry", "max_stars_repo_head_hexsha": "4a58ffd1d68d5cb2d12012af00c00743dbee8327", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T06:55:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-23T03:01:04.000Z", "max_issues_repo_path": "rotation_from_euler.cpp", "max_issues_repo_name": "yubaoliu/VisualizeGeometry", "max_issues_repo_head_hexsha": "4a58ffd1d68d5cb2d12012af00c00743dbee8327", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rotation_from_euler.cpp", "max_forks_repo_name": "yubaoliu/VisualizeGeometry", "max_forks_repo_head_hexsha": "4a58ffd1d68d5cb2d12012af00c00743dbee8327", "max_forks_repo_licenses": ["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.2352941176, "max_line_length": 106, "alphanum_fraction": 0.6026156942, "num_tokens": 337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885904, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.7650921444879883}} {"text": "#include \"sphere.hpp\"\n\n#include \"intersection_info.hpp\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\nnamespace shapes\n{\n\n// Check for ray-sphere intersection using geometric test.\n//\n// Note:\n// If ray origin is on the surface of the sphere and ray direction points\n// to the outside, no intersection is found.\nbool intersects(shapes::sphere shape, math::ray3d ray)\n{\n const auto L = math::make_vector3d(ray.origin, shape.center);\n const auto tPX = math::dot(L, ray.direction);\n\n const auto orig_center_sqrd_dist = math::squared_length(L);\n const auto squared_radius = shape.radius * shape.radius;\n\n // Ray origin is inside sphere.\n if (orig_center_sqrd_dist < squared_radius) { return true; }\n\n // Sphere center is behind ray origin.\n if (tPX <= 0.0f) { return false; }\n\n auto dsq = orig_center_sqrd_dist - tPX * tPX;\n return dsq <= squared_radius;\n}\n\n// Returns the closest intersection point between ray and sphere.\n//\n// Note:\n// If ray origin is on the surface of the sphere and ray direction points\n// to the outside, no intersection is found.\nboost::optional closest_intersection(shapes::sphere shape, math::ray3d ray)\n{\n const auto L = math::make_vector3d(ray.origin, shape.center);\n const auto tPX = math::dot(L, ray.direction);\n\n const auto orig_center_sqrd_dist = math::squared_length(L);\n const auto squared_radius = shape.radius * shape.radius;\n const auto origin_inside_sphere = orig_center_sqrd_dist < squared_radius;\n\n // Sphere center is behind ray origin.\n if (tPX <= 0.0f && origin_inside_sphere == false) { return boost::none; }\n\n const auto dsq = orig_center_sqrd_dist - tPX * tPX;\n if (dsq > squared_radius) { return boost::none; }\n\n float t;\n if (tPX > 0.0f && origin_inside_sphere == false)\n {\n t = tPX - std::sqrt(squared_radius - dsq);\n }\n else\n {\n t = tPX + std::sqrt(squared_radius - dsq);\n }\n\n shapes::intersection_info info;\n info.point = math::translated(ray.origin, math::scaled(ray.direction, t));\n info.normal = math::normalized(math::make_vector3d(shape.center, info.point));\n return info;\n}\n\n}\n", "meta": {"hexsha": "0b652fbaf034006ef39ee7e4b83ef64f19ad6680", "size": 2240, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/shapes/sphere.cpp", "max_stars_repo_name": "TiagoRabello/Path-Tracer", "max_stars_repo_head_hexsha": "1ad32741fdff0b8f48ef675e9071c1495cbcdde3", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/shapes/sphere.cpp", "max_issues_repo_name": "TiagoRabello/Path-Tracer", "max_issues_repo_head_hexsha": "1ad32741fdff0b8f48ef675e9071c1495cbcdde3", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-02-01T09:14:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-01T09:14:44.000Z", "max_forks_repo_path": "src/shapes/sphere.cpp", "max_forks_repo_name": "TiagoRabello/Path-Tracer", "max_forks_repo_head_hexsha": "1ad32741fdff0b8f48ef675e9071c1495cbcdde3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7179487179, "max_line_length": 102, "alphanum_fraction": 0.7133928571, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936261, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7649137324295866}} {"text": "#include \n#include \n#include \n#include \n\n// Generic functor\ntemplate\nstruct Functor\n{\n // Information that tells the caller the numeric type (eg. double) and size (input / output dim)\n typedef _Scalar Scalar;\n enum {\n InputsAtCompileTime = NX,\n ValuesAtCompileTime = NY\n};\n// Tell the caller the matrix sizes associated with the input, output, and jacobian\ntypedef Eigen::Matrix InputType;\ntypedef Eigen::Matrix ValueType;\ntypedef Eigen::Matrix JacobianType;\n\n// Local copy of the number of inputs\nint m_inputs, m_values;\n\n// Two constructors:\nFunctor() : m_inputs(InputsAtCompileTime), m_values(ValuesAtCompileTime) {}\nFunctor(int inputs, int values) : m_inputs(inputs), m_values(values) {}\n\n// Get methods for users to determine function input and output dimensions\nint inputs() const { return m_inputs; }\nint values() const { return m_values; }\n\n};\n\n///////////////////////// Levenberg Marquardt Example (1) f(x) = a x + b ///////////////////////////////\n\ntypedef std::vector > Point2DVector;\n\nPoint2DVector GeneratePoints();\n\nstruct SimpleLineFunctor : Functor\n{\n int operator()(const Eigen::VectorXd &z, Eigen::VectorXd &fvec) const\n {\n // \"a\" in the model is z(0), and \"b\" is z(1)\n double x_i,y_i,a,b;\n for(unsigned int i = 0; i < this->Points.size(); ++i)\n {\n y_i=this->Points[i](1);\n x_i=this->Points[i](0);\n a=z(0);\n b=z(1);\n fvec(i) =y_i-(a*x_i +b);\n }\n\n return 0;\n }\n\n Point2DVector Points;\n\n int inputs() const { return 2; } // There are two parameters of the model\n int values() const { return this->Points.size(); } // The number of observations\n};\n\nstruct SimpleLineFunctorNumericalDiff : Eigen::NumericalDiff {};\n\nPoint2DVector GeneratePoints(const unsigned int numberOfPoints)\n{\n Point2DVector points;\n // Model y = 2*x + 5 with some noise (meaning that the resulting minimization should be about (2,5)\n for(unsigned int i = 0; i < numberOfPoints; ++i)\n {\n double x = static_cast(i);\n Eigen::Vector2d point;\n point(0) = x;\n point(1) = 2.0 * x + 5.0 + drand48()/10.0;\n points.push_back(point);\n }\n\n return points;\n}\n\nvoid testSimpleLineFunctor()\n{\n std::cout << \"Testing f(x) = a x + b function...\" << std::endl;\n\n unsigned int numberOfPoints = 50;\n Point2DVector points = GeneratePoints(numberOfPoints);\n\n Eigen::VectorXd x(2);\n x.fill(2.0f);\n\n SimpleLineFunctorNumericalDiff functor;\n functor.Points = points;\n Eigen::LevenbergMarquardt lm(functor);\n\n Eigen::LevenbergMarquardtSpace::Status status = lm.minimize(x);\n std::cout << \"status: \" << status << std::endl;\n std::cout << \"x that minimizes the function: \" << std::endl << x << std::endl;\n std::cout <<\"lm.parameters.epsfcn: \" < &x_values, std::vector &y_values,double a=-1, double b=0.6, double c=2, unsigned int numberOfPoints=50 )\n{\n //point are x_start=-4, x_end=3\n double x_start=-4;\n double x_end=3;\n double x,y;\n\n for(unsigned int i = 0; i < numberOfPoints; ++i)\n {\n x = x_start+ static_cast(i)* ( x_end- x_start)/numberOfPoints;\n y = a*pow(x,2)+b*x+c + drand48()/10.0;\n x_values.push_back(x);\n y_values.push_back(y);\n }\n\n}\n\nvoid testQuadraticFunctor()\n{\n std::cout << \"Testing the f(x) = ax² + bx + c function...\" << std::endl;\n std::vector x_values;\n std::vector y_values;\n\n double a=-1;\n double b=0.6;\n double c=2;\n\n quadraticPointsGenerator(x_values, y_values,a,b,c);\n\n // 'm' is the number of data points.\n int m = x_values.size();\n\n // Move the data into an Eigen Matrix.\n // The first column has the input values, x. The second column is the f(x) values.\n Eigen::MatrixXd measuredValues(m, 2);\n for (int i = 0; i < m; i++) {\n measuredValues(i, 0) = x_values[i];\n measuredValues(i, 1) = y_values[i];\n }\n\n // 'n' is the number of parameters in the function.\n // f(x) = a(x^2) + b(x) + c has 3 parameters: a, b, c\n int n = 3;\n\n // 'parameters' is vector of length 'n' containing the initial values for the parameters.\n // The parameters 'x' are also referred to as the 'inputs' in the context of LM optimization.\n // The LM optimization inputs should not be confused with the x input values.\n Eigen::VectorXd parameters(n);\n parameters(0) = 0.0; // initial value for 'a'\n parameters(1) = 0.0; // initial value for 'b'\n parameters(2) = 0.0; // initial value for 'c'\n\n //\n // Run the LM optimization\n // Create a LevenbergMarquardt object and pass it the functor.\n //\n\n QuadraticFunctor functor;\n functor.measuredValues = measuredValues;\n functor.m = m;\n functor.n = n;\n\n Eigen::LevenbergMarquardt lm(functor);\n int status = lm.minimize(parameters);\n std::cout << \"LM optimization status: \" << status << std::endl;\n\n //\n // Results\n // The 'x' vector also contains the results of the optimization.\n //\n std::cout << \"Optimization results\" << std::endl;\n std::cout << \"\\ta: \" << parameters(0) << std::endl;\n std::cout << \"\\tb: \" << parameters(1) << std::endl;\n std::cout << \"\\tc: \" << parameters(2) << std::endl;\n\n std::cout << \"Actual values are\" << std::endl;\n std::cout << \"\\ta: \" << a << std::endl;\n std::cout << \"\\tb: \" << b << std::endl;\n std::cout << \"\\tc: \" << c << std::endl;\n std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\n\n}\n\n\n///////////////////////// Levenberg Marquardt Example (3) f(x,y) = (x + 2*y -7)^2 + (2*x + y - 5)^2 ///////////////////////////////\n\n\n// https://en.wikipedia.org/wiki/Test_functions_for_optimization\n// Booth Function\n// Implement f(x,y) = (x + 2*y -7)^2 + (2*x + y - 5)^2\nstruct BoothFunctor : Functor\n{\n // Simple constructor\n BoothFunctor(): Functor(2,2) {}\n\n // Implementation of the objective function\n int operator()(const Eigen::VectorXd &z, Eigen::VectorXd &fvec) const\n {\n double x = z(0); double y = z(1);\n /*\n * Evaluate the Booth function.\n * Important: LevenbergMarquardt is designed to work with objective functions that are a sum\n * of squared terms. The algorithm takes this into account: do not do it yourself.\n * In other words: objFun = sum(fvec(i)^2)\n */\n fvec(0) = x + 2*y - 7;\n fvec(1) = 2*x + y - 5;\n return 0;\n }\n};\n\nvoid testBoothFunctor() {\n std::cout << \"Testing the f(x,y) = (x + 2*y -7)^2 + (2*x + y - 5)^2 function...\" << std::endl;\n Eigen::VectorXd zInit(2); zInit << 1.87, 2.032;\n std::cout << \"zInit: \" << zInit.transpose() << std::endl;\n Eigen::VectorXd zSoln(2); zSoln << 1.0, 3.0;\n std::cout << \"zSoln: \" << zSoln.transpose() << std::endl;\n\n BoothFunctor functor;\n Eigen::NumericalDiff numDiff(functor);\n Eigen::LevenbergMarquardt,double> lm(numDiff);\n lm.parameters.maxfev = 1000;\n lm.parameters.xtol = 1.0e-10;\n std::cout << \"max fun eval: \" << lm.parameters.maxfev << std::endl;\n std::cout << \"x tol: \" << lm.parameters.xtol << std::endl;\n\n Eigen::VectorXd z = zInit;\n int ret = lm.minimize(z);\n std::cout << \"iter count: \" << lm.iter << std::endl;\n std::cout << \"return status: \" << ret << std::endl;\n std::cout << \"zSolver: \" << z.transpose() << std::endl;\n std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\n}\n\n\n\n///////////////////////// Levenberg Marquardt Example (4) f(x,y) = (x^2 + y - 11)^2 + (x + y^2 - 7)^2 ///////////////////////////////\n\n\n// https://en.wikipedia.org/wiki/Test_functions_for_optimization\n// Himmelblau's Function\n// Implement f(x,y) = (x^2 + y - 11)^2 + (x + y^2 - 7)^2\nstruct HimmelblauFunctor : Functor\n{\n // Simple constructor\n HimmelblauFunctor(): Functor(2,2) {}\n\n // Implementation of the objective function\n int operator()(const Eigen::VectorXd &z, Eigen::VectorXd &fvec) const\n {\n double x = z(0); double y = z(1);\n /*\n * Evaluate Himmelblau's function.\n * Important: LevenbergMarquardt is designed to work with objective functions that are a sum\n * of squared terms. The algorithm takes this into account: do not do it yourself.\n * In other words: objFun = sum(fvec(i)^2)\n */\n fvec(0) = x * x + y - 11;\n fvec(1) = x + y * y - 7;\n return 0;\n }\n};\n\nvoid testHimmelblauFunctor()\n{\n std::cout << \"Testing f(x,y) = (x^2 + y - 11)^2 + (x + y^2 - 7)^2 function...\" << std::endl;\n // Eigen::VectorXd zInit(2); zInit << 0.0, 0.0; // soln 1\n // Eigen::VectorXd zInit(2); zInit << -1, 1; // soln 2\n // Eigen::VectorXd zInit(2); zInit << -1, -1; // soln 3\n Eigen::VectorXd zInit(2); zInit << 1, -1; // soln 4\n std::cout << \"zInit: \" << zInit.transpose() << std::endl;\n std::cout << \"soln 1: [3.0, 2.0]\" << std::endl;\n std::cout << \"soln 2: [-2.805118, 3.131312]\" << std::endl;\n std::cout << \"soln 3: [-3.77931, -3.28316]\" << std::endl;\n std::cout << \"soln 4: [3.584428, -1.848126]\" << std::endl;\n\n HimmelblauFunctor functor;\n Eigen::NumericalDiff numDiff(functor);\n Eigen::LevenbergMarquardt,double> lm(numDiff);\n lm.parameters.maxfev = 1000;\n lm.parameters.xtol = 1.0e-10;\n std::cout << \"max fun eval: \" << lm.parameters.maxfev << std::endl;\n std::cout << \"x tol: \" << lm.parameters.xtol << std::endl;\n\n Eigen::VectorXd z = zInit;\n int ret = lm.minimize(z);\n std::cout << \"iter count: \" << lm.iter << std::endl;\n std::cout << \"return status: \" << ret << std::endl;\n std::cout << \"zSolver: \" << z.transpose() << std::endl;\n std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\n}\n\n\nint main()\n{\n testSimpleLineFunctor();\n testQuadraticFunctor();\n testBoothFunctor();\n testHimmelblauFunctor();\n}\n\n\n/*\n\nRefs\nhttps://github.com/daviddoria/Examples/blob/master/c%2B%2B/Eigen/LevenbergMarquardt/CurveFitting.cpp\nhttps://stackoverflow.com/questions/18509228/how-to-use-the-eigen-unsupported-levenberg-marquardt-implementation\nhttps://stackoverflow.com/questions/48213584/understanding-levenberg-marquardt-enumeration-returns\nhttps://www.ultimatepp.org/reference$Eigen_demo$en-us.html\nhttps://ethz-adrl.github.io/ct/ct_doc/doc/html/core_tut_linearization.html\nhttps://robotics.stackexchange.com/questions/20673/why-with-the-pseudo-inverse-it-is-possible-to-invert-the-jacobian-matrix-even-in\nhttp://users.ics.forth.gr/~lourakis/\nhttps://mathoverflow.net/questions/257699/gauss-newton-vs-gradient-descent-vs-levenberg-marquadt-for-least-squared-method\nhttps://math.stackexchange.com/questions/1085436/gauss-newton-versus-gradient-descent\nhttps://stackoverflow.com/questions/34701160/how-to-set-levenberg-marquardt-damping-using-eigen\nhttp://www.netlib.org/minpack/lmder.f\nhttps://en.wikipedia.org/wiki/Test_functions_for_optimization\nhttps://github.com/daviddoria/Examples/blob/master/c%2B%2B/Eigen/LevenbergMarquardt/NumericalDerivative.cpp\nhttps://stackoverflow.com/questions/18509228/how-to-use-the-eigen-unsupported-levenberg-marquardt-implementation\n*/\n\n", "meta": {"hexsha": "0e9cd615da23bbd1817d32328767a8790ae02f68", "size": 14543, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/levenberg_marquardt.cpp", "max_stars_repo_name": "behnamasadi/Mastering_Eigen", "max_stars_repo_head_hexsha": "99edbc819c89a4805b777eef69044a1658d96206", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-04-14T16:54:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T15:55:08.000Z", "max_issues_repo_path": "src/levenberg_marquardt.cpp", "max_issues_repo_name": "behnamasadi/Mastering_Eigen", "max_issues_repo_head_hexsha": "99edbc819c89a4805b777eef69044a1658d96206", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/levenberg_marquardt.cpp", "max_forks_repo_name": "behnamasadi/Mastering_Eigen", "max_forks_repo_head_hexsha": "99edbc819c89a4805b777eef69044a1658d96206", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-25T10:08:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-06T14:27:32.000Z", "avg_line_length": 35.7321867322, "max_line_length": 162, "alphanum_fraction": 0.6042769717, "num_tokens": 4149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.8840392832736084, "lm_q1q2_score": 0.7648920778324746}} {"text": "#include \n#include \n#include \n#include \n#include \"writer.hpp\"\n#include \n\n/// Uses the explicit Euler method to compute y from time 0 to time T\n/// where y is a 2x1 vector solving the linear system of ODEs as in the exercise\n///\n/// @param[out] yT at the end of the call, this will have vNext\n/// @param[in] y0 the initial conditions\n/// @param[in] zeta the damping factor (see exercise)\n/// @param[in] h the step size\n/// @param[in] T the final time at which to compute the solution.\n///\n/// The first component of y (the position) will be stored to y1, the second component (the velocity) to y2. The i-th entry of y1 (resp. y2) will contain the first (resp. second) component of y at time i*h.\n///\n\n//----------------explicitEulerBegin----------------\nvoid explicitEuler(std::vector & y1, std::vector &y2, std::vector & time,\n\tconst Eigen::Vector2d& y0,\n\t\t double zeta, double h, double T) {\n\n\ty1.push_back(y0(0));\n\ty2.push_back(y0(1));\n\ttime.push_back(0);\n\n\tfor(int k = 0; k < (T / h); k++) {\n\t\tdouble y1_k = y1.back();\n\t\tdouble y2_k = y2.back();\n\n\t\t//y1[k + 1] = y1_k + h * y2_k;\n\t\t//y2[k + 1] = y2_k + h * (-y1_k - (2 * zeta * y2_k));\n\n\t\t//time[k + 1] = time[k] + h;\n\n\t\ty1.push_back(y1_k + h * y2_k);\n\t\ty2.push_back(y2_k + h * (-y1_k - (2 * zeta * y2_k)));\n\n\t\ttime.push_back(time.back() + h);\n\t}\n}\n//----------------explicitEulerEnd----------------\n\n// Implements the implicit Euler. Analogous to explicit Euler, same input and output parameters\n//----------------implicitEulerBegin----------------\nvoid implicitEuler(std::vector & y1, std::vector & y2, std::vector & time,\n\tconst Eigen::Vector2d& y0,\n\t\t double zeta, double h, double T) {\n\n\tint nSteps = T / h;\n\t//y1.resize(nSteps + 1);\n\t//y2.resize(nSteps + 1);\n\t//time.resize(nSteps + 1);\n\n\ty1[0] = y0(0);\n\ty2[0] = y0(1);\n\ttime[0] = 0;\n\n\tEigen::MatrixXd A(2, 2);\n\tA << 1, -h,\n\t\t\t h, (1 + 2*zeta*h);\n\n\tEigen::FullPivLU lu = A.fullPivLu();\n\n\tfor(int k = 0; k < nSteps + 1; k++) {\n\t\tEigen::Vector2d y_prev = { y1[k], y2[k] };\n\t\tEigen::VectorXd y_next = lu.solve(y_prev);\n\t\ty1[k + 1] = y_next(0);\n\t\ty2[k + 1] = y_next(1);\n\t\ttime[k + 1] = time[k] + h;\n\t}\n}\n//----------------implicitEulerEnd----------------\n\n\n//----------------energyBegin----------------\n// Energy computation given the velocity. Assume the energy vector to be already initialized with the correct size.\nvoid Energy(const std::vector & v, std::vector & energy)\n{\n assert(v.size()==energy.size());\n\n\tfor(int i = 0; i < v.size(); i++) {\n\t\tenergy[i] = 0.5 * v[i] * v[i];\n\t}\n}\n//----------------energyEnd----------------\n\nint main() {\n\n\tdouble T = 20.0;\n\tdouble h = 0.5; // Change this for explicit / implicit time stepping comparison\n\tconst Eigen::Vector2d y0(1,0);\n\tdouble zeta=0.2;\n\tstd::vector y1;\n\tstd::vector y2;\n\tstd::vector time;\n\texplicitEuler(y1,y2,time,y0,zeta,h,T);\n\twriteToFile(\"position_expl.txt\", y1);\n\twriteToFile(\"velocity_expl.txt\",y2);\n\twriteToFile(\"time_expl.txt\",time);\n\tstd::vector energy(y2.size());\n\tEnergy(y2,energy);\n\twriteToFile(\"energy_expl.txt\",energy);\n\ty1.assign(y1.size(),0);\n\ty2.assign(y2.size(),0);\n\ttime.assign(time.size(),0);\n\tenergy.assign(energy.size(),0);\n\timplicitEuler(y1,y2,time,y0,zeta,h,T);\n\twriteToFile(\"position_impl.txt\", y1);\n\twriteToFile(\"velocity_impl.txt\",y2);\n\twriteToFile(\"time_impl.txt\",time);\n\tEnergy(y2,energy);\n\twriteToFile(\"energy_impl.txt\",energy);\n\n\treturn 0;\n}\n", "meta": {"hexsha": "55e320e874985c60dc073c18102ab2873aad4ede", "size": 3506, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "exercise_6/harmonic_oscill.cpp", "max_stars_repo_name": "azurite/numCSE18-code", "max_stars_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-13T19:08:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-13T19:08:32.000Z", "max_issues_repo_path": "exercise_6/harmonic_oscill.cpp", "max_issues_repo_name": "azurite/numCSE18-code", "max_issues_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercise_6/harmonic_oscill.cpp", "max_forks_repo_name": "azurite/numCSE18-code", "max_forks_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_forks_repo_licenses": ["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.4621848739, "max_line_length": 206, "alphanum_fraction": 0.6158014832, "num_tokens": 1095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254318, "lm_q2_score": 0.8652240808393984, "lm_q1q2_score": 0.7648920644010749}} {"text": "#include \n#include \n#include \n#include \n#include \n\nnamespace toynet {\n\nublas::vector softmax(const ublas::vector& v)\n{\n return stable_softmax(v);\n}\n\nublas::vector naive_softmax(const ublas::vector& v)\n{\n double sum = 0;\n for (auto x : v)\n sum += exp(x);\n ublas::vector ret(v.size());\n for (int i = 0; i < v.size(); ++i)\n ret[i] = exp(v[i]) / sum;\n return ret;\n}\n\nublas::vector stable_softmax(const ublas::vector &v)\n{\n double max = v.empty() ? 0.0 : *std::max_element(v.begin(), v.end());\n double sum = 0;\n for (auto x : v)\n sum += exp(x - max);\n ublas::vector ret(v.size());\n for (int i = 0; i < v.size(); ++i)\n ret[i] = exp(v[i] - max) / sum;\n return ret;\n}\n\ndouble magnitude(const ublas::vector& v)\n{\n return ublas_magnitude(v);\n}\n\ndouble naive_magnitude(const ublas::vector& v)\n{\n double ret = 0.0;\n for (auto x : v)\n ret += x * x;\n return sqrt(ret);\n}\n\ndouble ublas_magnitude(const ublas::vector& v)\n{\n return ublas::norm_2(v);\n}\n\ndouble dot_product(const ublas::vector& v1, const ublas::vector& v2)\n{\n return ublas_dot_product(v1, v2);\n}\n\ndouble naive_dot_product(const ublas::vector& v1, const ublas::vector& v2)\n{\n double ret = 0.0;\n for (int i = 0; i < v1.size(); ++i)\n ret += v1[i] * v2[i];\n return ret;\n}\n\ndouble ublas_dot_product(const ublas::vector& v1, const ublas::vector& v2)\n{\n return ublas::inner_prod(v1, v2);\n}\n\ndouble cosine_distance(const ublas::vector& v1, const ublas::vector& v2)\n{\n return dot_product(v1, v2) / (magnitude(v1) * magnitude(v2));\n}\n\nstd::vector nearest_neighbors(const ublas::vector& v, const std::vector>& points)\n{\n std::vector> distances(points.size());\n for (int i = 0; i < points.size(); ++i)\n distances[i] = std::make_pair(cosine_distance(v, points[i]), i);\n std::sort(distances.begin(), distances.end(), std::greater<>());\n std::vector ret(points.size());\n for (int i = 0; i < points.size(); ++i)\n ret[i] = distances[i].second;\n return ret;\n}\n\nvoid add(std::vector>& to, const std::vector>& other)\n{\n for (int i = 0; i < to.size(); ++i)\n to[i] += other[i];\n}\n\nvoid add(std::vector>& to, const std::vector>& other)\n{\n for (int i = 0; i < to.size(); ++i)\n to[i] += other[i];\n}\n\nvoid normalize(std::vector>& to, double denom)\n{\n for (auto& d : to)\n d /= denom;\n}\n\nvoid normalize(std::vector>& to, double denom)\n{\n for (auto& d : to)\n d /= denom;\n}\n\n} // namespace toynet\n", "meta": {"hexsha": "400e1ae8c2be31f157a21817c1b3414f2c85878e", "size": 2942, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toynet/math.cpp", "max_stars_repo_name": "pbrunelle/w2v", "max_stars_repo_head_hexsha": "2ae0d95283c67ae5e27823a81edf05821280dae0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "toynet/math.cpp", "max_issues_repo_name": "pbrunelle/w2v", "max_issues_repo_head_hexsha": "2ae0d95283c67ae5e27823a81edf05821280dae0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-11-28T18:42:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T23:02:51.000Z", "max_forks_repo_path": "toynet/math.cpp", "max_forks_repo_name": "pbrunelle/toynet", "max_forks_repo_head_hexsha": "2ae0d95283c67ae5e27823a81edf05821280dae0", "max_forks_repo_licenses": ["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.5826086957, "max_line_length": 116, "alphanum_fraction": 0.6091094494, "num_tokens": 874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317103, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7645757238696804}} {"text": "/*\n * Copyright Nick Thompson, 2020\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\nusing boost::multiprecision::float128;\nconstexpr const int GRAPH_WIDTH = 300;\n\ntemplate\nvoid plot_phi(int grid_refinements = -1)\n{\n auto phi = boost::math::daubechies_scaling();\n if (grid_refinements >= 0)\n {\n phi = boost::math::daubechies_scaling(grid_refinements);\n }\n Real a = 0;\n Real b = phi.support().second;\n std::string title = \"Daubechies \" + std::to_string(p) + \" scaling function\";\n title = \"\";\n std::string filename = \"daubechies_\" + std::to_string(p) + \"_scaling.svg\";\n int samples = 1024;\n quicksvg::graph_fn daub(a, b, title, filename, samples, GRAPH_WIDTH);\n daub.set_gridlines(8, 2*p-1);\n daub.set_stroke_width(1);\n daub.add_fn(phi);\n daub.write_all();\n}\n\ntemplate\nvoid plot_dphi(int grid_refinements = -1)\n{\n auto phi = boost::math::daubechies_scaling();\n if (grid_refinements >= 0)\n {\n phi = boost::math::daubechies_scaling(grid_refinements);\n }\n Real a = 0;\n Real b = phi.support().second;\n std::string title = \"Daubechies \" + std::to_string(p) + \" scaling function derivative\";\n title = \"\";\n std::string filename = \"daubechies_\" + std::to_string(p) + \"_scaling_prime.svg\";\n int samples = 1024;\n quicksvg::graph_fn daub(a, b, title, filename, samples, GRAPH_WIDTH);\n daub.set_stroke_width(1);\n daub.set_gridlines(8, 2*p-1);\n auto dphi = [phi](Real x)->Real { return phi.prime(x); };\n daub.add_fn(dphi);\n daub.write_all();\n}\n\ntemplate\nvoid plot_convergence()\n{\n auto phi0 = boost::math::daubechies_scaling(0);\n Real a = 0;\n Real b = phi0.support().second;\n std::string title = \"Daubechies \" + std::to_string(p) + \" scaling at 0 (green), 1 (orange), 2 (red), and 24 (blue) grid refinements\";\n title = \"\";\n std::string filename = \"daubechies_\" + std::to_string(p) + \"_scaling_convergence.svg\";\n\n quicksvg::graph_fn daub(a, b, title, filename, 1024, 900);\n daub.set_stroke_width(1);\n daub.set_gridlines(8, 2*p-1);\n\n daub.add_fn(phi0, \"green\");\n auto phi1 = boost::math::daubechies_scaling(1);\n daub.add_fn(phi1, \"orange\");\n auto phi2 = boost::math::daubechies_scaling(2);\n daub.add_fn(phi2, \"red\");\n\n auto phi21 = boost::math::daubechies_scaling(21);\n daub.add_fn(phi21);\n\n daub.write_all();\n}\n\ntemplate\nvoid plot_condition_number()\n{\n using std::abs;\n using std::log;\n static_assert(p >= 3, \"p = 2 is not differentiable, so condition numbers cannot be effectively evaluated.\");\n auto phi = boost::math::daubechies_scaling();\n Real a = std::sqrt(std::numeric_limits::epsilon());\n Real b = phi.support().second - 1000*std::sqrt(std::numeric_limits::epsilon());\n std::string title = \"log10 of condition number of function evaluation for Daubechies \" + std::to_string(p) + \" scaling function.\";\n title = \"\";\n std::string filename = \"daubechies_\" + std::to_string(p) + \"_scaling_condition_number.svg\";\n\n\n quicksvg::graph_fn daub(a, b, title, filename, 2048, GRAPH_WIDTH);\n daub.set_stroke_width(1);\n daub.set_gridlines(8, 2*p-1);\n\n auto cond = [&phi](Real x)\n {\n Real y = phi(x);\n Real dydx = phi.prime(x);\n Real z = abs(x*dydx/y);\n using std::isnan;\n if (z==0)\n {\n return Real(-1);\n }\n if (isnan(z))\n {\n // Graphing libraries don't like nan's:\n return Real(1);\n }\n return log10(z);\n };\n daub.add_fn(cond);\n daub.write_all();\n}\n\ntemplate\nvoid do_ulp(int coarse_refinements, PhiPrecise phi_precise)\n{\n auto phi_coarse = boost::math::daubechies_scaling(coarse_refinements);\n\n std::string title = std::to_string(p) + \" vanishing moment ULP plot at \" + std::to_string(coarse_refinements) + \" refinements and \" + boost::core::demangle(typeid(CoarseReal).name()) + \" precision\";\n title = \"\";\n\n std::string filename = \"daubechies_\" + std::to_string(p) + \"_\" + boost::core::demangle(typeid(CoarseReal).name()) + \"_\" + std::to_string(coarse_refinements) + \"_refinements.svg\";\n int samples = 20000;\n int clip = 10;\n int horizontal_lines = 8;\n int vertical_lines = 2*p - 1;\n auto [a, b] = phi_coarse.support();\n auto plot = boost::math::tools::ulps_plot(phi_precise, a, b, samples);\n plot.clip(clip).width(GRAPH_WIDTH).horizontal_lines(horizontal_lines).vertical_lines(vertical_lines).ulp_envelope(false);\n\n plot.background_color(\"white\").font_color(\"black\");\n plot.add_fn(phi_coarse);\n plot.write(filename);\n}\n\n\nint main()\n{\n boost::hana::for_each(std::make_index_sequence<18>(), [&](auto i){ plot_phi(); });\n boost::hana::for_each(std::make_index_sequence<17>(), [&](auto i){ plot_dphi(); });\n boost::hana::for_each(std::make_index_sequence<17>(), [&](auto i){ plot_condition_number(); });\n boost::hana::for_each(std::make_index_sequence<18>(), [&](auto i){ plot_convergence(); });\n\n using PreciseReal = float128;\n using CoarseReal = double;\n int precise_refinements = 23;\n constexpr const int p = 8;\n std::cout << \"Computing precise scaling function in \" << boost::core::demangle(typeid(PreciseReal).name()) << \" precision.\\n\";\n auto phi_precise = boost::math::daubechies_scaling(precise_refinements);\n std::cout << \"Beginning comparison with functions computed in \" << boost::core::demangle(typeid(CoarseReal).name()) << \" precision.\\n\";\n for (int i = 7; i <= precise_refinements-1; ++i)\n {\n std::cout << \"\\tCoarse refinement \" << i << \"\\n\";\n do_ulp(i, phi_precise);\n }\n}\n", "meta": {"hexsha": "d4ef5fde25df7152e9de90fa00d2109656fbadf8", "size": 6457, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/daubechies_wavelets/daubechies_scaling_plots.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "example/daubechies_wavelets/daubechies_scaling_plots.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/example/daubechies_wavelets/daubechies_scaling_plots.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 37.5406976744, "max_line_length": 202, "alphanum_fraction": 0.6566516958, "num_tokens": 1853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7645398716219107}} {"text": "#include \"polynomial.h\"\n#include \n\nnamespace Chaf\n{\n\tPolynomialInterpolation::PolynomialInterpolation(const std::vector& points)\n\t{\n\t\t// Ax=y, we want x\n\t\tsize_t dim = points.size();\n\t\tEigen::MatrixXd A(dim, dim);\n\t\tEigen::VectorXd y(dim);\n\t\tm_params.resize(dim);\n\n\t\tfor (uint32_t i = 0; i < points.size(); i++)\n\t\t{\n\t\t\tfor (uint32_t j = 0; j < points.size(); j++)\n\t\t\t{\n\t\t\t\tA(i, j) = pow(points[i].x, (double)j);\n\t\t\t}\n\n\t\t\ty(i) = points[i].y;\n\t\t}\n\n\t\tEigen::VectorXd x = A.colPivHouseholderQr().solve(y);\n\n\t\tfor (uint32_t i = 0; i < points.size(); i++)\n\t\t{\n\t\t\tm_params[i] = x(i);\n\t\t}\n\t}\n\n\tdouble PolynomialInterpolation::evaluate(double x)\n\t{\n\t\tdouble result = 0.f;\n\n\t\tfor (uint32_t i = 0; i < m_params.size(); i++)\n\t\t{\n\t\t\tresult += m_params[i] * std::pow(x, static_cast(i));\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tstd::vector PolynomialInterpolation::evaluate(const std::vector& x)\n\t{\n\t\tstd::vector result(x.size());\n\n\t\tfor (uint32_t i = 0; i < result.size(); i++)\n\t\t{\n\t\t\tresult[i] = evaluate(x[i]);\n\t\t}\n\t\treturn result;\n\t}\n}", "meta": {"hexsha": "fd570684dc49e40ca83de00d0e14beab0b8e2a1c", "size": 1070, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homework/Homeworks/Homework1/polynomial.cpp", "max_stars_repo_name": "Chaphlagical/CAGD", "max_stars_repo_head_hexsha": "55b79364a13fe062f6f7b8d061fb7bed236aa61d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-01T14:05:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T14:05:50.000Z", "max_issues_repo_path": "Homework/Homeworks/Homework1/polynomial.cpp", "max_issues_repo_name": "Chaphlagical/CAGD", "max_issues_repo_head_hexsha": "55b79364a13fe062f6f7b8d061fb7bed236aa61d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homework/Homeworks/Homework1/polynomial.cpp", "max_forks_repo_name": "Chaphlagical/CAGD", "max_forks_repo_head_hexsha": "55b79364a13fe062f6f7b8d061fb7bed236aa61d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-01T14:47:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T14:47:48.000Z", "avg_line_length": 19.8148148148, "max_line_length": 90, "alphanum_fraction": 0.6056074766, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7643846917279128}} {"text": "/**\n * Write a function 'filter()' that implements a multi-\n * dimensional Kalman Filter for the example given\n */\n\n#include \n#include \n#include \n\nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing Eigen::VectorXd;\nusing Eigen::MatrixXd;\n\n// Kalman Filter variables\nVectorXd x;\t// object state\nMatrixXd P;\t// object covariance matrix\nVectorXd u;\t// external motion\nMatrixXd F; // state transition matrix\nMatrixXd H;\t// measurement matrix\nMatrixXd R;\t// measurement covariance matrix\nMatrixXd I; // Identity matrix\nMatrixXd Q;\t// process covariance matrix\n\nvector measurements;\nvoid filter(VectorXd &x, MatrixXd &P);\n\n\nint main() {\n /**\n * Code used as example to work with Eigen matrices\n */\n // design the KF with 1D motion\n x = VectorXd(2);\n x << 0, 0;\n P = MatrixXd(2, 2);\n P << 1000, 0, 0, 1000;\n u = VectorXd(2);\n u << 0, 0;\n F = MatrixXd(2, 2);\n F << 1, 1, 0, 1;\n H = MatrixXd(1, 2);\n H << 1, 0;\n R = MatrixXd(1, 1);\n R << 1;\n I = MatrixXd::Identity(2, 2);\n Q = MatrixXd(2, 2);\n Q << 0, 0, 0, 0;\n // create a list of measurements\n VectorXd single_meas(1);\n single_meas << 1;\n measurements.push_back(single_meas);\n single_meas << 2;\n measurements.push_back(single_meas);\n single_meas << 3;\n measurements.push_back(single_meas);\n\n // call Kalman filter algorithm\n filter(x, P);\n\n return 0;\n}\n\n\nvoid filter(VectorXd &x, MatrixXd &P) {\n\n for (unsigned int n = 0; n < measurements.size(); ++n) {\n\n VectorXd z = measurements[n];\n // TODO: YOUR CODE HERE\n\n // KF Measurement update step\n x=x+(P*H.transpose()*(H*P*H.transpose()+R).inverse())*(z-H*x);\n P=(I-(P*H.transpose()*(H*P*H.transpose()+R).inverse())*H)*P;\n // new state\n\n // KF Prediction step\n x=F*x+u;\n P=F*P*F.transpose();\n cout << \"x=\" << endl << x << endl;\n cout << \"P=\" << endl << P << endl;\n }\n}\n\n//x=\n//0.999001\n// 0\n//P=\n//1001 1000\n//1000 1000\n//x=\n// 2.998\n//0.999002\n//P=\n//4.99002 2.99302\n//2.99302 1.99501\n//x=\n//3.99967\n// 1\n//P=\n// 2.33189 0.999168\n//0.999168 0.499501\n\n", "meta": {"hexsha": "64e384858a833097581c9fb6b473cd7c87b28f8c", "size": 2069, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Workspace Exercises/Part1.cpp", "max_stars_repo_name": "SmokeShine/CarND-Extended-Kalman-Filter-Project", "max_stars_repo_head_hexsha": "c629f795d493369ee6ebb4ee853da6c0eee86f7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Workspace Exercises/Part1.cpp", "max_issues_repo_name": "SmokeShine/CarND-Extended-Kalman-Filter-Project", "max_issues_repo_head_hexsha": "c629f795d493369ee6ebb4ee853da6c0eee86f7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Workspace Exercises/Part1.cpp", "max_forks_repo_name": "SmokeShine/CarND-Extended-Kalman-Filter-Project", "max_forks_repo_head_hexsha": "c629f795d493369ee6ebb4ee853da6c0eee86f7d", "max_forks_repo_licenses": ["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.7047619048, "max_line_length": 66, "alphanum_fraction": 0.6118898018, "num_tokens": 706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802363, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7638638079188035}} {"text": "\r\n// Copyright Christopher Kormanyos 2013.\r\n// Copyright Paul A. Bristow 2013.\r\n// Copyright John Maddock 2013.\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#ifdef _MSC_VER\r\n# pragma warning (disable : 4512) // assignment operator could not be generated.\r\n# pragma warning (disable : 4996) // assignment operator could not be generated.\r\n#endif\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n// Weisstein, Eric W. \"Bessel Function Zeros.\" From MathWorld--A Wolfram Web Resource.\r\n// http://mathworld.wolfram.com/BesselFunctionZeros.html\r\n// Test values can be calculated using [@wolframalpha.com WolframAplha]\r\n// See also http://dlmf.nist.gov/10.21\r\n\r\n//[airy_zeros_example_1\r\n\r\n/*`This example demonstrates calculating zeros of the Airy functions.\r\nIt also shows how Boost.Math and Boost.Multiprecision can be combined to provide\r\na many decimal digit precision. For 50 decimal digit precision we need to include\r\n*/\r\n\r\n #include \r\n\r\n/*`and a `typedef` for `float_type` may be convenient\r\n(allowing a quick switch to re-compute at built-in `double` or other precision)\r\n*/\r\n typedef boost::multiprecision::cpp_dec_float_50 float_type;\r\n\r\n//`To use the functions for finding zeros of the functions we need\r\n\r\n #include \r\n\r\n/*`This example shows obtaining both a single zero of the Airy functions,\r\nand then placing multiple zeros into a container like `std::vector` by providing an iterator.\r\nThe signature of the single-value Airy Ai function is:\r\n\r\n template \r\n T airy_ai_zero(unsigned m); // 1-based index of the zero.\r\n\r\nThe signature of multiple zeros Airy Ai function is:\r\n\r\n template \r\n OutputIterator airy_ai_zero(\r\n unsigned start_index, // 1-based index of the zero.\r\n unsigned number_of_zeros, // How many zeros to generate.\r\n OutputIterator out_it); // Destination for zeros.\r\n\r\nThere are also versions which allows control of the __policy_section for error handling and precision.\r\n\r\n template \r\n OutputIterator airy_ai_zero(\r\n unsigned start_index, // 1-based index of the zero.\r\n unsigned number_of_zeros, // How many zeros to generate.\r\n OutputIterator out_it, // Destination for zeros.\r\n const Policy& pol); // Policy to use.\r\n*/\r\n//] [/airy_zeros_example_1]\r\n\r\nint main()\r\n{\r\n try\r\n {\r\n//[airy_zeros_example_2\r\n\r\n/*`[tip It is always wise to place code using Boost.Math inside `try'n'catch` blocks;\r\nthis will ensure that helpful error messages are shown when exceptional conditions arise.]\r\n\r\nFirst, evaluate a single Airy zero.\r\n\r\nThe precision is controlled by the template parameter `T`,\r\nso this example has `double` precision, at least 15 but up to 17 decimal digits\r\n(for the common 64-bit double).\r\n*/\r\n double aiz1 = boost::math::airy_ai_zero(1);\r\n std::cout << \"boost::math::airy_ai_zero(1) = \" << aiz1 << std::endl; \r\n double aiz2 = boost::math::airy_ai_zero(2);\r\n std::cout << \"boost::math::airy_ai_zero(2) = \" << aiz2 << std::endl;\r\n double biz3 = boost::math::airy_bi_zero(3);\r\n std::cout << \"boost::math::airy_bi_zero(3) = \" << biz3 << std::endl;\r\n\r\n/*`Other versions of `airy_ai_zero` and `airy_bi_zero`\r\nallow calculation of multiple zeros with one call,\r\nplacing the results in a container, often `std::vector`.\r\nFor example, generate and display the first five `double` roots\r\n[@http://mathworld.wolfram.com/AiryFunctionZeros.html Wolfram Airy Functions Zeros].\r\n*/\r\n unsigned int n_roots = 5U;\r\n std::vector roots;\r\n boost::math::airy_ai_zero(1U, n_roots, std::back_inserter(roots));\r\n std::cout << \"airy_ai_zeros:\" << std::endl;\r\n std::copy(roots.begin(),\r\n roots.end(),\r\n std::ostream_iterator(std::cout, \"\\n\"));\r\n\r\n/*`The first few real roots of Ai(x) are approximately -2.33811, -4.08795, -5.52056, -6.7867144, -7.94413, -9.02265 ...\r\n\r\nOr we can use Boost.Multiprecision to generate 50 decimal digit roots.\r\n\r\nWe set the precision of the output stream, and show trailing zeros to display a fixed 50 decimal digits.\r\n*/\r\n std::cout.precision(std::numeric_limits::digits10); // float_type has 50 decimal digits.\r\n std::cout << std::showpoint << std::endl; // Show trailing zeros too.\r\n\r\n unsigned int m = 1U;\r\n float_type r = boost::math::airy_ai_zero(1U); // 1st root.\r\n std::cout << \"boost::math::airy_bi_zero(\" << m << \") = \" << r << std::endl;\r\n r = boost::math::airy_ai_zero(1U); // 1st root.\r\n std::cout << \"boost::math::airy_bi_zero(\" << m << \") = \" << r << std::endl;\r\n m = 7U;\r\n r = boost::math::airy_bi_zero(7U); // 7th root.\r\n std::cout << \"boost::math::airy_bi_zero(\" << m << \") = \" << r << std::endl;\r\n\r\n std::vector zeros;\r\n boost::math::airy_ai_zero(1U, 3, std::back_inserter(zeros));\r\n std::cout << \"airy_ai_zeros:\" << std::endl;\r\n // Print the roots to the output stream.\r\n std::copy(zeros.begin(), zeros.end(),\r\n std::ostream_iterator(std::cout, \"\\n\"));\r\n//] [/airy_zeros_example_2]\r\n }\r\n catch (std::exception ex)\r\n {\r\n std::cout << \"Thrown exception \" << ex.what() << std::endl;\r\n }\r\n\r\n } // int main()\r\n\r\n/*\r\n\r\n Output:\r\n\r\n Description: Autorun \"J:\\Cpp\\big_number\\Debug\\airy_zeros_example.exe\"\r\n boost::math::airy_ai_zero(1) = -2.33811\r\n boost::math::airy_ai_zero(2) = -4.08795\r\n boost::math::airy_bi_zero(3) = -4.83074\r\n\r\n airy_ai_zeros:\r\n -2.33811\r\n -4.08795\r\n -5.52056\r\n -6.78671\r\n -7.94413\r\n \r\n boost::math::airy_bi_zero(1) = -2.3381074104597665552773833042010664939880371093750\r\n boost::math::airy_bi_zero(1) = -2.3381074104597670384891972524467354406385502908783\r\n boost::math::airy_bi_zero(7) = -9.5381943793462388866329885451560196208390720763825\r\n\r\n airy_ai_zeros:\r\n -2.3381074104597670384891972524467354406385502908783\r\n -4.0879494441309706166369887014573910602247646991085\r\n -5.5205598280955510591298555129312935737972142806175\r\n\r\n\r\n\r\n*/\r\n\r\n", "meta": {"hexsha": "f68cfb959c0fa796401299cc42ebdd5e7b141f16", "size": 6571, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/airy_zeros_example.cpp", "max_stars_repo_name": "Abce/boost", "max_stars_repo_head_hexsha": "2d7491a27211aa5defab113f8e2d657c3d85ca93", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/math/example/airy_zeros_example.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/math/example/airy_zeros_example.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 38.8816568047, "max_line_length": 120, "alphanum_fraction": 0.6758484249, "num_tokens": 1744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122138417878, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7637986934768758}} {"text": "#include \"perceptron.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\nusing namespace Eigen;\n\nmt19937 rng;\n\nperceptron::perceptron()\n{\n\tnum_epochs = 5;\n}\n\nvoid perceptron::fit(MatrixXf& X_train, VectorXi& y_train)\n{\n\tcout << \"fit\" << endl;\n\tint n = X_train.rows(), dim = X_train.cols();\n\t\n\ttheta0 = 0.0; \n\ttheta = VectorXf::Zero(dim, 1);\n\t\n\tuniform_int_distribution unif(0, n-1);\n\tint k = 1;\n\tfor (int epoch = 0; epoch < num_epochs; ++epoch)\n\t{\n\t\tfor (int i = 0; i < n; ++i)\n\t\t{\n\t\t\tint idx = unif(rng); //sample random point\n\t\t\tif (y_train[idx] * (theta.dot(X_train.row(idx)) + theta0) <= 1.0) //hinge loss\n\t\t\t{\n\t\t\t\tfloat eta = pow(k + 1, -1); k++; //update learning rate\n\t\t\t\ttheta = theta + eta * y_train[idx] * X_train.row(idx).transpose(); //update theta\n\t\t\t\ttheta0 = theta0 + eta * y_train[idx]; //update intercept\n\t\t\t\tcout << \"eta: \" << eta << endl;\n\t\t\t}\n\t\t}\n\t\tcout << \"epoch: \" << epoch << endl;\n\t\tcout << \"theta: \" << endl << theta << endl << \" theta0: \" << theta0 << endl;\n\t}\n}\nvoid perceptron::predict(MatrixXf& X_test, VectorXi& y_test)\n{\n\tcout << \"predict\" << endl;\n\tint n = X_test.rows(), dim = X_test.cols();\n\n\tint num_errors = 0;\n\tfor (int i = 0; i < n; ++i)\n\t{\n\t\tif (y_test[i] * (theta.dot(X_test.row(i)) + theta0) < 0)\n\t\t{\n\t\t\tnum_errors++;\n\t\t}\n\t}\n\tfloat yerr = (float)num_errors / float(n);\n\tcout << \"Perceptron classification error: \" << yerr << endl;\n}\n\n\nvoid load_iris(MatrixXf& X_train, VectorXi& y_train)\n{\n\t//read-in labels\n\tint cnt = 0;\n\tstring line;\n\tifstream fin1(\"./data/iris_labels.txt\");\n\tif (fin1.is_open())\n\t{\n\t\twhile (getline(fin1, line))\n\t\t{\n\t\t\ty_train(cnt) = stoi(line);\n\t\t\tcnt++;\n\t\t}\n\t\tfin1.close();\n\t}\n\telse cout << \"Unable to open fin1\\n\";\n\tcout << \"y = \" << endl << y_train << endl;\n\tcout << \"y.size = \" << y_train.size() << endl;\n\n\t//read-in data\n\tcnt = 0;\n\tint nrows = 0;\n\tint ncols = 0;\n\tifstream fin2(\"./data/iris_data.txt\");\n\tif (fin2.is_open())\n\t{\n\t\tfin2 >> nrows >> ncols;\n\t\tfor (int row = 0; row < nrows; row++)\n\t\t\tfor (int col = 0; col < ncols; col++)\n\t\t\t{\n\t\t\t\tfloat num = 0.0;\n\t\t\t\tfin2 >> num;\n\t\t\t\tX_train(row, col) = num;\n\t\t\t}\n\t\tfin2.close();\n\t}\n\telse cout << \"Unable to open fin2\\n\";\n\tcout << \"X = \" << endl << X_train << endl;\n\tcout << \"X.size = \" << X_train.rows() << \" x \" << X_train.cols() << endl;\n}\n\nint main()\n{\n cout << \"Perceptron Algorithm\" << endl;\n\n\t//load iris\t\n\tint nrows = 0, ncols = 0;\n\tstring line;\n\tifstream fin1(\"./data/iris_data.txt\");\n\tif (fin1.is_open())\n\t{\n\t\tfin1 >> nrows >> ncols;\n\t\tfin1.close();\n\t}\n\telse cout << \"Unable to open data file\\n\";\n\tcout << \"nrows = \" << nrows << endl;\n\tcout << \"ncols = \" << ncols << endl;\n\n\tMatrixXf X_train = MatrixXf::Zero(nrows, ncols); //training data n x d\n\tVectorXi y_train = VectorXi::Zero(nrows); //training labels n x 1\n\n\tload_iris(X_train, y_train);\n\n\tperceptron P = perceptron();\n\tP.fit(X_train, y_train); \n\tP.predict(X_train, y_train); //TODO: predict on test data\n\n\treturn 0;\n}\n", "meta": {"hexsha": "80cc23f8a52f63a8f9c90c338dc84656b7d2f3fa", "size": 3028, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "machine_learning/perceptron/perceptron.cpp", "max_stars_repo_name": "vishalbelsare/cpp", "max_stars_repo_head_hexsha": "772178d911e8f90c23e9d3c1d8d32482bc397fc5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2017-11-14T03:20:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-06T09:46:17.000Z", "max_issues_repo_path": "machine_learning/perceptron/perceptron.cpp", "max_issues_repo_name": "kunalyadav684/cpp", "max_issues_repo_head_hexsha": "3ce14b012acb2dcdf91459fb677de4bd0cb46170", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-01T22:30:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-01T22:30:50.000Z", "max_forks_repo_path": "machine_learning/perceptron/perceptron.cpp", "max_forks_repo_name": "kunalyadav684/cpp", "max_forks_repo_head_hexsha": "3ce14b012acb2dcdf91459fb677de4bd0cb46170", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2018-02-07T22:44:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-19T10:18:16.000Z", "avg_line_length": 22.7669172932, "max_line_length": 86, "alphanum_fraction": 0.5931307794, "num_tokens": 989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303728259492, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7637021502177246}} {"text": "#include \n\n#include \n#include \n\n#include \n\n//! \\brief Solve the autonomous IVP y' = f(y), y(0) = y0 using Rosenbrock method\n//! Use semi-implicit Rosenbrock method using Jacobian evaluation. Equidistant steps of size T/N.\n//! \\tparam Func function type for r.h.s. f\n//! \\tparam DFunc function type for Jacobian df\n//! \\tparam StateType type of solution space y and initial data y0\n//! \\param[in] f r.h.s. func f\n//! \\param[in] df Jacobian df of f\n//! \\param[in] y0 initial data y(0)\n//! \\param[in] N number of equidistant steps\n//! \\param[in] T final time\n//! \\return vector of y_k for each step k from 0 to N\ntemplate \nstd::vector solveRosenbrock(const Func & f, const DFunc & df,\n const StateType & y0, unsigned int N, double T) {\n const double h = T/N;\n const double a = 1. / (std::sqrt(2) + 2.);\n \n // Will contain all time steps\n std::vector res(N+1);\n // Push initial data\n res.at(0) = y0;\n \n // Some temporary\n StateType k1, k2;\n Eigen::Matrix2d J, W;\n \n // Main loop: *up to N (performs N steps)*\n for(unsigned int i = 1; i <= N; ++i) {\n StateType & yprev = res.at(i-1);\n \n // Jacobian computation\n J = df(yprev);\n W = Eigen::Matrix2d::Identity() - a*h*J;\n \n // Reuse factorization for each step\n auto W_lu = W.partialPivLu();\n \n // Increments\n k1 = W_lu.solve(f(yprev));\n k2 = W_lu.solve(f(yprev+0.5*h*k1) - a*h*J*k1);\n \n // Push new step\n res.at(i) = yprev + h*k2;\n }\n \n return res;\n}\n\n\nint main() {\n // Final time\n const double T = 10;\n // All mesh sizes\n const std::vector N = {16, 32, 64, 128, 256, 512, 1024, 2048, 4096};\n // Reference mesh size\n const int N_ref = 16384;\n // Initial data\n Eigen::Vector2d y0;\n y0 << 1., 1.;\n // Parameter and useful matrix for f\n const double lambda = 1;\n Eigen::Matrix2d R;\n R << 0., -1., 1., 0.;\n\n // Function and his Jacobian\n auto f = [&R, &lambda] (const Eigen::Vector2d & y) { return R*y + lambda*(1. - std::pow(y.norm(),2))*y; };\n auto df = [&lambda] (const Eigen::Vector2d & y) {\n double x = 1 - std::pow(y.norm(), 2);\n Eigen::Matrix2d J;\n J << lambda*x - 2*lambda*y(0)*y(0),\n -1 - 2*lambda*y(1)*y(0),\n 1 - 2*lambda*y(1)*y(0),\n lambda*x - 2*lambda*y(1)*y(1);\n return J;\n };\n\n // Reference solution\n auto solref = solveRosenbrock(f, df, y0, N_ref, T);\n\n std::cout << std::setw(15) << \"n\" << std::setw(15) << \"maxerr\" << std::setw(15) << \"rate\" << std::endl;\n // Used to compute rate at each step:\n double errold = 0;\n // Main loop: loop over all meshes\n for(unsigned int i = 0; i < N.size(); ++i) {\n int n = N.at(i);\n \n // Get solution\n auto sol = solveRosenbrock(f, df, y0, n, T);\n \n // Compute error\n double maxerr = 0;\n for(unsigned int j = 0; j < sol.size(); ++j) {\n maxerr = std::max(maxerr, (sol.at(j) - solref.at((j*N_ref)/n)).norm());\n }\n \n // Do some I/O\n std::cout << std::setw(15) << n << std::setw(15) << maxerr;\n if(i > 0) std::cout << std::setw(15) << std::log2(errold / maxerr);\n std::cout << std::endl;\n \n // Save old error (for rate)\n errold = maxerr;\n }\n}\n \n", "meta": {"hexsha": "e0ddfd01538532124926a789cf21b89e1fea59f3", "size": 3523, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS14/solutions_ps14/rosenbrock.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS14/solutions_ps14/rosenbrock.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS14/solutions_ps14/rosenbrock.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1769911504, "max_line_length": 111, "alphanum_fraction": 0.5322168606, "num_tokens": 1114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422644, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7634301675371626}} {"text": "#include \n#include \nusing namespace std;\n\n//#include \n//#include \n\n#include \n#include \n\nusing Sophus::SO3d;\nusing Sophus::SE3d;\n\nint main(int argc, char** argv) {\n // 沿Z轴转90度的旋转矩阵\n Eigen::Matrix3d R =\n Eigen::AngleAxisd(M_PI / 2, Eigen::Vector3d(0, 0, 1)).toRotationMatrix();\n\n SO3d SO3_R(R); // SO(3)可以直接从旋转矩阵构造\n SO3d SO3_v(SO3d::exp({0, 0, M_PI / 2})); // 亦可从旋转向量构造\n Eigen::Quaterniond q(R); // 或者四元数\n SO3d SO3_q(q);\n // 上述表达方式都是等价的\n // 输出SO(3)时,以so(3)形式输出\n cout << \"SO(3) from matrix: \" << SO3_R.log() << endl;\n cout << \"SO(3) from vector: \" << SO3_v.log() << endl;\n cout << \"SO(3) from quaternion :\" << SO3_q.log() << endl;\n\n // 使用对数映射获得它的李代数\n Eigen::Vector3d so3 = SO3_R.log();\n cout << \"so3 = \" << so3.transpose() << endl;\n // hat 为向量到反对称矩阵\n cout << \"so3 hat=\\n\" << SO3d::hat(so3) << endl;\n // 相对的,vee为反对称到向\n cout << \"so3 hat vee= \" << SO3d::vee(SO3d::hat(so3)).transpose()\n << endl; // transpose纯粹是为了输出美观一些\n\n // 增量扰动模型的更新\n Eigen::Vector3d update_so3(1e-4, 0, 0); //假设更新量为这么多\n SO3d SO3_updated = SO3d::exp(update_so3) * SO3_R;\n cout << \"SO3 updated = \" << SO3_updated.log() << endl;\n\n /********************萌萌的分割线*****************************/\n cout << \"*************************\" << endl;\n // 对SE(3)操作大同小异\n Eigen::Vector3d t(1, 0, 0); // 沿X轴平移1\n SE3d SE3_Rt(R, t); // 从R,t构造SE(3)\n SE3d SE3_qt(q, t); // 从q,t构造SE(3)\n cout << \"SE3 from R,t= \" << endl << SE3_Rt.log() << endl;\n cout << \"SE3 from q,t= \" << endl << SE3_qt.log() << endl;\n // 李代数se(3) 是一个六维向量,方便起见先typedef一下\n typedef Eigen::Matrix Vector6d;\n Vector6d se3 = SE3_Rt.log();\n cout << \"se3 = \" << se3.transpose() << endl;\n // 观察输出,会发现在Sophus中,se(3)的平移在前,旋转在后.\n // 同样的,有hat和vee两个算符\n cout << \"se3 hat = \" << endl << SE3d::hat(se3) << endl;\n cout << \"se3 hat vee = \" << SE3d::vee(SE3d::hat(se3)).transpose() << endl;\n\n // 最后,演示一下更新\n Vector6d update_se3; //更新量\n update_se3.setZero();\n update_se3(0, 0) = 1e-4d;\n SE3d SE3_updated = SE3d::exp(update_se3) * SE3_Rt;\n cout << \"SE3 updated = \" << endl << SE3_updated.matrix() << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "b862e5c54799152a462d90b19a8cc5f4fbdb9b59", "size": 2192, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch4/useSophus/useSophus.cpp", "max_stars_repo_name": "duyanwei/slambook", "max_stars_repo_head_hexsha": "0e257f885d7b31ef6272311c49ce4654d690ef97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch4/useSophus/useSophus.cpp", "max_issues_repo_name": "duyanwei/slambook", "max_issues_repo_head_hexsha": "0e257f885d7b31ef6272311c49ce4654d690ef97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch4/useSophus/useSophus.cpp", "max_forks_repo_name": "duyanwei/slambook", "max_forks_repo_head_hexsha": "0e257f885d7b31ef6272311c49ce4654d690ef97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.768115942, "max_line_length": 79, "alphanum_fraction": 0.5702554745, "num_tokens": 995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.916109622750986, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7634166768482852}} {"text": "//\n// Created by vasy1 on 2/14/2019.\n//\n#include \n#include \n#include \n#include \n#include \n\nnamespace utilities\n{\n static constexpr double pi() { return M_PI; }\n\n inline double deg2rad(double x) { return x * pi() / 180; }\n\n inline double rad2deg(double x) { return x * 180 / pi(); }\n\n// Evaluate a polynomial.\n static double polyeval(Eigen::VectorXd coeffs, double x)\n {\n double result = 0.0;\n for (int i = 0; i < coeffs.size(); i++)\n {\n result += coeffs[i] * pow(x, i);\n }\n return result;\n }\n\n static Eigen::VectorXd polyfit(const Eigen::VectorXd &xvals, const Eigen::VectorXd &yvals,\n int order)\n {\n assert(xvals.size() == yvals.size());\n assert(order >= 1 && order <= xvals.size() - 1);\n Eigen::MatrixXd A(xvals.size(), order + 1);\n\n for (int i = 0; i < xvals.size(); i++)\n {\n A(i, 0) = 1.0;\n }\n\n for (int j = 0; j < xvals.size(); j++)\n {\n for (int i = 0; i < order; i++)\n {\n A(j, i + 1) = A(j, i) * xvals(j);\n }\n }\n\n auto Q = A.householderQr();\n auto result = Q.solve(yvals);\n return result;\n }\n\n static std::vector> rotate_coords(const std::vector &coords)\n {\n //adjust points in ref to be in front of car, apply angle transformation\n const double sin_psi = sin(deg2rad(-90));\n const double cos_psi = cos(deg2rad(-90));\n std::vector waypoints_x;\n std::vector waypoints_y;\n for (auto &coord : coords)\n {\n waypoints_x.push_back(coord.x * cos_psi - coord.y * sin_psi);\n waypoints_y.push_back(coord.x * sin_psi + coord.y * cos_psi);\n }\n\n double *ptrx = &waypoints_x[0];\n double *ptry = &waypoints_y[0];\n Eigen::Map waypoints_x_eig(ptrx, 6);\n Eigen::Map waypoints_y_eig(ptry, 6);\n return {waypoints_x_eig, waypoints_y_eig};\n }\n}\n\n\n\n\n", "meta": {"hexsha": "79fa467f432f3397b82e0f7a71838da2c56d1e32", "size": 2148, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lane_follower/src/utilities.hpp", "max_stars_repo_name": "vasi1796/eurobotics_demo", "max_stars_repo_head_hexsha": "617cc4c42cecf82e7e0fd7ef037a0da2a1182c1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-05T06:10:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-05T06:10:16.000Z", "max_issues_repo_path": "lane_follower/src/utilities.hpp", "max_issues_repo_name": "vasi1796/eurobotics_demo", "max_issues_repo_head_hexsha": "617cc4c42cecf82e7e0fd7ef037a0da2a1182c1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lane_follower/src/utilities.hpp", "max_forks_repo_name": "vasi1796/eurobotics_demo", "max_forks_repo_head_hexsha": "617cc4c42cecf82e7e0fd7ef037a0da2a1182c1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-07-09T06:50:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-05T06:10:22.000Z", "avg_line_length": 27.5384615385, "max_line_length": 105, "alphanum_fraction": 0.5409683426, "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.763388461799754}} {"text": "#include \"rubbishrsa/maths.hpp\"\n#include \"rubbishrsa/log.hpp\"\n\n// Rubbish rng\n#include \n// Crypto rng\n#include \n#include \n\n#include \n#include \n\nnamespace rubbishrsa {\n bigint modinv(const bigint& a, const bigint& n) {\n auto res = egcd(a, n);\n if (res.gcd != 1)\n throw std::invalid_argument(\"Cannot compute modular inverse of non-coprime numbers!\");\n\n // The second coefficient would represent the number of multiples of the modulus,\n // but we don't care about that\n //\n // In addition to this, the egcd will may return a negative number in the same\n // congruence class. We will normalise this\n if (res.coefficients.first >= 0)\n return res.coefficients.first;\n else\n return n + res.coefficients.first;\n }\n\n // lcm(a,b) = a/gcd(a,b) * b\n bigint lcm(const bigint& a, const bigint& b) {\n return (a / egcd(a, b).gcd) * b;\n }\n\n using egcd_matrix_t = std::array, 2>;\n\n // Pretty-prints the array\n void egcd_log_matrix(const egcd_matrix_t& state) {\n std::array, 2> string_matrix;\n std::array max_len = { 0, 0, 0 };\n // Pass 1: get the maximum length, and generate the strings\n for (size_t row_i = 0; row_i < 2; ++row_i) {\n for (size_t column_i = 0; column_i < 3; ++column_i) {\n auto& res = (string_matrix[row_i][column_i] = state[row_i][column_i].str());\n auto& target = max_len[column_i];\n if (res.size() > target)\n target = res.size();\n }\n }\n\n std::cerr << \"| \"\n << std::setw(max_len[0]) << string_matrix[0][0] << \" \"\n << std::setw(max_len[1]) << string_matrix[0][1]\n << \" | \" << std::setw(max_len[2]) << string_matrix[0][2] << \" |\"\n << std::endl\n << \"| \"\n << std::setw(max_len[0]) << string_matrix[1][0] << \" \"\n << std::setw(max_len[1]) << string_matrix[1][1]\n << \" | \" << std::setw(max_len[2]) << string_matrix[1][2] << \" |\"\n << std::endl\n << std::endl;\n }\n\n egcd_result egcd(const bigint& a, const bigint& b) {\n // This is basically a code version of the lecture notes on the topic\n\n RUBBISHRSA_LOG_TRACE(std::cerr << \"Calculating GCD of \" << a.str() << \" and \" << b.str() << std::endl);\n\n if (a <= 0 || b <= 0)\n throw std::invalid_argument(\"GCD cannot be computed with non-positive argument!\");\n\n std::arraycol[2];\n\n\n egcd_matrix_t matrix = {{\n {1, 0, a},\n {0, 1, b}\n }};\n\n RUBBISHRSA_LOG_TRACE(egcd_log_matrix(matrix));\n\n egcd_result return_value;\n\n while (true) {\n // Calculate the number of multiples of the b cell that fits into the a cell\n auto a_fit = matrix[0][2] / matrix[1][2];\n\n // Subtract that from the a row\n for (size_t i = 0; i < 3; ++i) {\n matrix[0][i] -= matrix[1][i] * a_fit;\n }\n\n RUBBISHRSA_LOG_TRACE(egcd_log_matrix(matrix));\n\n // Check the a cell to see if we're done\n if (matrix[0][2] == 0)\n return {\n .gcd = matrix[1][2],\n .coefficients = {matrix[1][0], matrix[1][1]}\n };\n\n // Now we do the same thing for the b row\n auto b_fit = matrix[1][2] / matrix[0][2];\n for (size_t i = 0; i < 3; ++i) {\n matrix[1][i] -= matrix[0][i] * b_fit;\n }\n\n RUBBISHRSA_LOG_TRACE(egcd_log_matrix(matrix));\n\n // Check the b cell to see if we're done\n if (matrix[1][2] == 0)\n return {\n .gcd = matrix[0][2],\n .coefficients = {matrix[0][0], matrix[0][1]}\n };\n }\n }\n\n // I will use boost random for this stuff, and stl's one doesn't support the bigint\n bool is_prime(const bigint& candidate, uint_fast8_t certainty_log_4) {\n // This in an implementation of the Miller-Rabin probabilistic primality test\n bigint odd = candidate;\n size_t exponent = 0;\n\n // We keep the the non-power of 2 in i\n while (odd % 2 != 0) {\n ++exponent;\n // A quicker way of doing i = 2\n odd >>= 1;\n }\n\n bigint min = 2;\n bigint max = candidate - 2;\n // We don't need a crypto rng here\n thread_local boost::random::mt19937 rng;\n const boost::random::uniform_int_distribution dist(std::move(min), std::move(max));\n\n // We do this a lot, so precompute it\n bigint candidate_minus_1 = candidate - 1;\n\n bigint x;\n for (uint_fast8_t iter = 0; iter < certainty_log_4; ++iter) {\n bigint a = dist(rng);\n x = bmp::powm(a, odd, candidate);\n // If we already have a congruence, then we have passed this iter\n if (x == 1 || x == candidate_minus_1)\n continue;\n\n for (decltype(exponent) i = 1; i < exponent; ++i) {\n x = bmp::powm(x, 2, candidate);\n if (x == candidate_minus_1)\n // Only way to quickly leave a nested loop\n //\n // Please don't just take away marks because I used a goto!\n //\n // gotos to escape nested loops are perfectly fine, and make\n // the code _far_ more readable than a separate func, or a\n // boolean check at the end (which would also be slower)\n goto next_iter;\n }\n // If we failed all of our subiterations, then we must exit out of the loop\n return false;\nnext_iter: {}\n }\n\n return true;\n }\n\n bigint generate_prime(uint_fast16_t bits) {\n // (1 << n) means 2^n, giving us a range of 2^(n-2) to 2^(n-1) inclusive\n //\n // The reason for keeping this half of the desired values is that 2 is the only even prime,\n // so we can save a lot of composite candidates by multiplying by 2 and adding 1\n bigint min = 1; min <<= (bits - 2);\n bigint max = min; max <<= 1;\n\n RUBBISHRSA_LOG_TRACE(\n std::cerr << \"Generating prime candidate bases between \" << min.str()\n << \" and \" << max.str() << std::endl\n );\n\n // Our distribution is that of all numbers with the given bit count\n const boost::random::uniform_int_distribution dist(std::move(min), std::move(max));\n\n // TO speed up prime generation, we run on each core of the cpu until we find a prime\n std::vector pool;\n bigint ret;\n std::atomic stop = false;\n for (unsigned int i = 0; i < std::thread::hardware_concurrency(); ++i) {\n pool.emplace_back([&, i]() {\n // Removes warnings about i not being used\n (void)i;\n // (Almost) always a cryptographically secure rng\n thread_local boost::random::random_device rng;\n // Moving this outside may create some nebulous speed improvement\n bigint candidate;\n // We stop looping when a single thread has found a result, and marked stop as true\n while (!stop) {\n // Get a random number, and make it odd\n candidate = dist(rng) * 2 + 1;\n // We will only log the candidates of one thread so that we keep the output synchronised\n RUBBISHRSA_LOG_TRACE(if (i == 0) std::cerr << \"\\tPrime candidate \" << candidate.str() << std::endl);\n // Check if we have a prime, and check if we are the first thread to have one\n if (is_prime(candidate, 128) && !stop.exchange(true)) {\n ret = std::move(candidate);\n }\n }\n });\n }\n\n // Wait for each thread to finish\n for (auto& thread : pool) thread.join();\n\n RUBBISHRSA_LOG_TRACE(std::cerr << \"Chose \" << ret << \" as prime\" << std::endl);\n\n return ret;\n }\n\n bigint pollard_rho(const bigint& n) {\n std::vector pool;\n std::atomic found = false;\n bigint result;\n\n // Using primes will minimise the chance of collision, which means that threads are less likely to do redundant work\n // I have hand removed 5, as it is the second term of 2's sequence\n constexpr static std::array primes{2, 3, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719};\n auto max_threads = std::min(static_cast(std::thread::hardware_concurrency()), primes.size());\n // Do Pollard's rho algorithm with each thread, each with a different polynomial\n for (size_t i = 0; i < max_threads; ++i) {\n pool.emplace_back([&, i]() {\n bigint x = primes[i];\n bigint y = x;\n bigint gcd;\n\n while (!found) {\n // We are trying to find two elements in the sequence u_n such that u_i is congruent to u_j (mod p), but u_n is not equal to u_i\n //\n // With two such elements, we have (as a result of the remainder property of moduli) gcd(|u_i - u_j|, n) is not 1.\n //\n // This means that there is some common divisor between them, and the result of this gcd is a factor of n\n //\n // We step one position (x) forward by 1, and the other (y) by 2, to increase the size of the tested cycle.\n //\n // For some unknown reason, If we pick u_n = u_n^2 + a (mod n) as our random generator, we will find a result quicker.\n\n // 1 iter for x\n x = (x*x + 1) % n;\n // 2 iters for y\n y = (y*y + 1) % n;\n y = (y*y + 1) % n;\n\n // We don't need to worry about both elements being equal (unless it is prime),\n // as we will happen upon a factor cycle far before that (with high probability)\n gcd = egcd(bmp::abs(x - y), n).gcd;\n // If we found something with a non-trivial gcd, that's a factor\n if (gcd != 1 && !found.exchange(true))\n result = gcd;\n }\n });\n }\n\n for (auto& thread : pool)\n thread.join();\n\n return result;\n }\n\n // TODO: implement\n// bigint quadratic_sieve(const bigint& n) {\n// abort();\n\n// // Not a perfect calcuation, but easy to do\n// bmp::mpf_float log_n = bmp::log(bmp::mpf_float{n});\n// bmp::mpf_float bound = bmp::exp(bmp::mpf_float{1/2} * log_n * bmp::log(log_n));\n\n// bigint prime_count_approx{bmp::ceil(bmp::mpf_float{n} / log_n)};\n\n// for (bigint i = 0; i < bound; ++i) {\n\n// }\n// }\n\n std::pair factorise_semiprime(const bigint& semiprime) {\n size_t bits = floor_log2(semiprime);\n\n // Pollard takes a bit too long when bits >= 83 on my system, and I'll knock off a few \"Windows points\"\n if (bits < 70) {\n auto p = pollard_rho(semiprime);\n auto q = semiprime / p;\n return {p, q};\n }\n // TODO: make this use quadratic sieve\n else {\n auto p = pollard_rho(semiprime);\n auto q = semiprime / p;\n return {p, q};\n }\n }\n\n bigint ascii2bigint(std::string_view str) {\n bigint data = 0;\n for (auto i : str) {\n // Cast the character to an unsigned integer type, and add it to the end of the number\n data <<= 8;\n data += static_cast(i);\n }\n return data;\n }\n\n bigint ascii2bigint(std::istream& in) {\n bigint data = 0;\n // Keep going until the end of the file\n while (!in.eof()) {\n data <<= 8;\n data += in.get();\n }\n return data;\n }\n\n std::string bigint2ascii(bigint data) {\n std::string str;\n str.reserve(2048);\n // Read the string backwards\n while (data) {\n str.push_back(static_cast(data & 0xFF));\n data >>= 8;\n }\n std::reverse(str.begin(), str.end());\n return str;\n }\n\n bigint hex2bigint(std::string_view str) {\n // A slow way of doing it, but this is not a bottleneck\n std::string con_str{\"0x\"};\n con_str += str;\n return bigint{con_str};\n }\n}\n", "meta": {"hexsha": "3fe3f7d1a808129a92317b16aba3413e57151f11", "size": 12062, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/maths.cpp", "max_stars_repo_name": "Cyclic3/rubbishrsa", "max_stars_repo_head_hexsha": "d1755b6ed464c84fa7a44e8665631f28766ee7fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/maths.cpp", "max_issues_repo_name": "Cyclic3/rubbishrsa", "max_issues_repo_head_hexsha": "d1755b6ed464c84fa7a44e8665631f28766ee7fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/maths.cpp", "max_forks_repo_name": "Cyclic3/rubbishrsa", "max_forks_repo_head_hexsha": "d1755b6ed464c84fa7a44e8665631f28766ee7fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.581120944, "max_line_length": 657, "alphanum_fraction": 0.5865528105, "num_tokens": 3563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676518712608, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7633616840082519}} {"text": "#include \n#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\n#define MATRIX_SIZE 100\n\n// 编程实现 A 为 100 × 100 随机矩阵时,⽤ QR 和 Cholesky 分解求 x 的程序\nint main(int argc, char const *argv[])\n{\n // 创建随机矩阵 A[100x100] 并输出\n Matrix A\n = MatrixXd::Random(MATRIX_SIZE, MATRIX_SIZE);\n // cout << \"Matrix A is: \\n\" << A << endl;\n\n // 创建随机\n Matrix B = MatrixXd::Random(MATRIX_SIZE, 1);\n // cout << \"Matrix B is: \\n\" << B << endl;\n\n // 求解 Ax = B\n // 1. QR 分解\n auto x = A.colPivHouseholderQr().solve(B);\n cout << \"QR decompostion: \\n x = \" << x << endl << endl; \n\n // 2. Cholesky 分解\n auto y = A.ldlt().solve(B);\n cout << \"Cholesky decompostion: \\n x = \" << y << endl; \n\n return 0;\n}\n\n", "meta": {"hexsha": "55cb068517c32f4c9789d4e7b02b717ed9f08391", "size": 813, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Notes/chap3/code/Q1/main.cc", "max_stars_repo_name": "Alexbeast-CN/Notes2SLAM", "max_stars_repo_head_hexsha": "43651d8548431b26538739cc3130d315de4d4f7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Notes/chap3/code/Q1/main.cc", "max_issues_repo_name": "Alexbeast-CN/Notes2SLAM", "max_issues_repo_head_hexsha": "43651d8548431b26538739cc3130d315de4d4f7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Notes/chap3/code/Q1/main.cc", "max_forks_repo_name": "Alexbeast-CN/Notes2SLAM", "max_forks_repo_head_hexsha": "43651d8548431b26538739cc3130d315de4d4f7f", "max_forks_repo_licenses": ["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.9117647059, "max_line_length": 72, "alphanum_fraction": 0.5928659287, "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350351, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7633025797278137}} {"text": "/***************************************************************************\n/* Javier Juan Albarracin - jajuaal1@ibime.upv.es */\n/* Universidad Politecnica de Valencia, Spain */\n/* */\n/* Copyright (C) 2020 Javier Juan Albarracin */\n/* */\n/***************************************************************************\n* Math *\n***************************************************************************/\n\n#ifndef MATH_HPP\n#define MATH_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define MATH_FLINTMAX 9.0072e+15\n#define MATH_EPS 2.220446049250313e-16\n#define MATH_INF 1e300\n\n#if _WIN32\n#define __PRETTY_FUNCTION__ std::string(__FUNCTION__)\n#endif\n\nusing namespace Eigen;\n\ntemplate\nint round(const T value)\n{\n return (int) std::ceil(value - 0.5);\n}\n\ntemplate\nint sign(const T value)\n{\n return value == 0 ? 0 : value > 0 ? 1 : -1;\n}\n\n/***************************** Histogram Edges class *****************************/\n\nclass Edges\n{\npublic:\n template\n static VectorXd binpicker(const T minx, const T maxx, const double rawBinWidth);\n template\n static VectorXd autorule(const DenseBase& x, const typename Derived::Scalar minx, const typename Derived::Scalar maxx, const bool hardlimits);\n template\n static VectorXd scottsrule(const DenseBase& x, const typename Derived::Scalar minx, const typename Derived::Scalar maxx, const bool hardlimits);\n template\n static VectorXd integerrule(const DenseBase& x, const typename Derived::Scalar minx, const typename Derived::Scalar maxx, const bool hardlimits);\n template\n static VectorXd sturgesrule(const DenseBase& x, const typename Derived::Scalar minx, const typename Derived::Scalar maxx, const bool hardlimits);\n template\n static VectorXd sqrtrule(const DenseBase& x, const typename Derived::Scalar minx, const typename Derived::Scalar maxx, const bool hardlimits);\n};\n\n/***************************** Math class *****************************/\n\nclass Math\n{\npublic:\n enum Order { ASCENDING, DESCENDING };\n enum Interpolation { PCHIP, MAKIMA };\n enum Kernel { NORMAL, BOX };\n\n template\n static bool isClose(const T x, const T y, const double rtol = 1.e-5, const double atol = 1.e-8);\n // Sort, reorder, permute, align\n template\n static typename Derived::PlainObject sort(const DenseBase& x, const Order order = Math::ASCENDING);\n template\n static typename Derived1::PlainObject sort(const DenseBase& x, DenseBase &indices, const Order order = Math::ASCENDING);\n // Basic statistics\n template\n static double mean(const DenseBase& x);\n template\n static double median(const DenseBase& x);\n template\n static typename Derived::Scalar mode(const DenseBase& x);\n template\n static double var(const DenseBase& x);\n template\n static double std(const DenseBase& x);\n template\n static double mad(const DenseBase& x);\n template\n static double percentile(const DenseBase& x, const double p);\n template\n static double percentile(const DenseBase& x, const double p, int& index);\n // Linspace\n template\n static VectorXd linspace(const T minx, const T maxx, const int N = 100);\n // Discrete integral and derivatives\n template\n static double integral(const DenseBase& x, const DenseBase& y);\n template\n static double integral(const DenseBase& y, const double step = 1);\n template\n static Matrix diff(const DenseBase& x);\n template\n static VectorXd gradient(const DenseBase& y);\n template\n static VectorXd gradient(const DenseBase& x, const DenseBase& y);\n // Distribution density estimation\n template\n static std::tuple histogram(const DenseBase& x);\n template\n static std::tuple histogram(const DenseBase& x, const VectorXd& edges);\n template\n static std::tuple cdf(const DenseBase& x);\n template\n static std::tuple cdf(const DenseBase& x, const VectorXd& edges);\n // Convolutions\n template\n static VectorXd conv1d(const DenseBase& x, const Kernel type = Math::NORMAL, const int size = 5, const double alpha = 2.5);\n template\n static VectorXd conv1d(const DenseBase& x, const VectorXd &k);\n // Interpolation\n template\n static VectorXd interp1(const DenseBase& x, const DenseBase& y, const DenseBase &xq, const Interpolation type = Math::MAKIMA);\n};\n\n/***************************** Implementation *****************************/\ntemplate\nbool Math::isClose(const T x, const T y, const double rtol, const double atol)\n{\n return std::abs(x - y) <= (atol + rtol * std::abs(y));\n}\n\ntemplate\ntypename Derived::PlainObject Math::sort(const DenseBase& x, const Order order)\n{\n if (order != ASCENDING && order != DESCENDING)\n {\n std::stringstream s;\n s << __PRETTY_FUNCTION__ << \": Unsupported parameter.\" << std::endl;\n throw std::runtime_error(s.str());\n }\n\n typename Derived::PlainObject y = x.derived();\n\n std::sort(y.data(), y.data() + y.size());\n return order == Math::ASCENDING ? y : y.reverse();\n}\n\ntemplate\ntypename Derived1::PlainObject Math::sort(const DenseBase& x, DenseBase &indices, const Order order)\n{\n if (order != ASCENDING && order != DESCENDING)\n {\n std::stringstream s;\n s << __PRETTY_FUNCTION__ << \": Unsupported parameter.\" << std::endl;\n throw std::runtime_error(s.str());\n }\n\n typename Derived1::PlainObject y = x.derived();\n typename Derived2::PlainObject& z = indices.derived();\n\n z.resize(y.rows(), y.cols());\n#pragma omp parallel for\n for (Index i = 0; i < z.size(); ++i)\n z(i) = i;\n \n std::sort(z.data(), z.data() + z.size(), [&](size_t a, size_t b) { return y(a) < y(b); });\n \n#pragma omp parallel for\n for (Index i = 0; i < z.size(); ++i)\n y(i) = x((Index) z(i));\n \n return order == Math::ASCENDING ? y : y.reverse();\n}\n\ntemplate\ndouble Math::mean(const DenseBase& x)\n{\n const typename Derived::PlainObject& y = x.derived();\n return (double) y.template cast().mean();\n}\n\ntemplate\ndouble Math::median(const DenseBase& x)\n{\n typename Derived::PlainObject y = x.derived();\n\n std::sort(y.data(), y.data() + y.size());\n if (((int) y.size() % 2) == 0)\n return (double) (y((Index)(y.size() / 2)) + y((Index)(y.size() / 2) - 1)) / 2.0;\n else\n return (double) y((Index)(y.size() / 2));\n}\n\ntemplate\ntypename Derived::Scalar Math::mode(const DenseBase& x)\n{\n typename Derived::PlainObject y = x.derived();\n \n std::sort(y.data(), y.data() + y.size());\n \n int max = 1;\n int counter = 1;\n typename Derived::Scalar mode = y(0);\n for (Index i = 1; i < y.size(); ++i)\n {\n if (y(i) == y(i - 1))\n {\n ++counter;\n if (counter > max)\n {\n max = counter;\n mode = y(i);\n }\n }\n else\n {\n counter = 1;\n }\n }\n return mode;\n}\n\ntemplate\ndouble Math::var(const DenseBase& x)\n{\n const double mu = Math::mean(x);\n double diff = 0;\n for (Index i = 0; i < x.size(); ++i)\n diff += (((double) x(i) - mu) * ((double) x(i) - mu));\n return diff / ((double) x.size() - 1.0);\n}\n\ntemplate\ndouble Math::std(const DenseBase& x)\n{\n return std::sqrt(Math::var(x));\n}\n\ntemplate\ndouble Math::mad(const DenseBase& x)\n{\n const typename Derived::PlainObject& y = x.derived();\n return Math::median((y - Math::median(y)).abs());\n}\n\ntemplate\ndouble Math::percentile(const DenseBase& x, const double p)\n{\n int index = 0;\n return Math::percentile(x, p, index);\n}\n\ntemplate\ndouble Math::percentile(const DenseBase& x, const double p, int& index)\n{\n if (p < 0 || p > 100)\n {\n std::stringstream s;\n s << __PRETTY_FUNCTION__ << \": Percentile must be in the range [0, 100]\" << std::endl;\n throw std::runtime_error(s.str());\n }\n\n if (x.size() == 1)\n return (double) x(0);\n\n VectorXi indices;\n const typename Derived::PlainObject& y = Math::sort(x, indices);\n \n if (p == 50)\n {\n index = indices((int) (y.size() / 2));\n if (((int) y.size() % 2) == 0)\n return (double) (y((Index) (y.size() / 2)) + y((Index)(y.size() / 2) - 1)) / 2.0;\n else\n return (double) y((Index) (y.size() / 2));\n }\n \n // Get index corresponding to p-percentile\n double r = (p / 100.0) * (double) (y.size() - 1);\n const int k = (int) std::floor(r);\n const int kp1 = k + 1 >= (int) y.size() ? (int) y.size() - 1 : k + 1;\n r = r - k;\n\n // Set index\n index = indices(k);\n\n // By interpolation\n return r == 0 ? (double) y(k) : (r * (double) y(kp1)) + ((1.0 - r) * (double) y(k));\n}\n\ntemplate\nVectorXd Math::linspace(const T minx, const T maxx, const int N)\n{\n if (N < 3)\n {\n std::stringstream s;\n s << __PRETTY_FUNCTION__ << \": Number of space points must be greater or equal than 3\" << std::endl;\n throw std::runtime_error(s.str());\n }\n\n VectorXd y(N);\n \n const int N1 = N - 1;\n const T c = (maxx - minx) * (T)(N1 - 1);\n if (!std::isfinite(c))\n {\n if (!std::isfinite(maxx - minx))\n {\n for (Index i = 0; i < N; ++i)\n y(i) = (double) minx + ((double) maxx / (double) N1) * i - ((double) minx / (double) N1) * i;\n }\n else\n {\n for (Index i = 0; i < N; ++i)\n y(i) = (double) minx + i * ((double) (maxx - minx) / (double) N1);\n }\n }\n else\n {\n for (Index i = 0; i < N; ++i)\n y(i) = (double) minx + i * ((double) (maxx - minx) / (double) N1);\n }\n if (y.size() > 0 )\n {\n y(0) = (double) minx;\n y(N1) = (double) maxx;\n }\n return y;\n}\n\ntemplate\ndouble Math::integral(const DenseBase& x, const DenseBase& y)\n{\n if (x.size() != y.size())\n {\n std::stringstream s;\n s << __PRETTY_FUNCTION__ << \" ==> x and y must be of the same size.\" << std::endl;\n throw std::runtime_error(s.str());\n }\n\n double result = 0;\n for (Index i = 0; i < y.size() - 1; ++i)\n result += (double) (x(i+1) - x(i)) * (y(i+1) + y(i));\n return result / 2.0;\n}\n\ntemplate\ndouble Math::integral(const DenseBase& y, const double step)\n{\n double result = 0;\n for (Index i = 0; i < y.size() - 1; ++i)\n result += (double) step * (y(i+1) + y(i));\n return result / 2.0;\n}\n\ntemplate\nMatrix Math::diff(const DenseBase& x)\n{\n if (x.rows() != 1 && x.cols() != 1)\n {\n std::stringstream s;\n s << __PRETTY_FUNCTION__ << \" ==> x must be a row or column vector/array.\" << std::endl;\n throw std::runtime_error(s.str());\n }\n\n Matrix d(x.size() - 1);\n#pragma omp parallel for\n for (Index i = 0; i < x.size() - 1; ++i)\n d(i) = x(i+1) - x(i);\n return d;\n}\n\ntemplate\nVectorXd Math::gradient(const DenseBase &y)\n{\n if (y.rows() != 1 && y.cols() != 1)\n {\n std::stringstream s;\n s << __PRETTY_FUNCTION__ << \" ==> x must be row or column vector/array.\" << std::endl;\n throw std::runtime_error(s.str());\n }\n\n const int N = y.size();\n if (N == 1)\n return y.derived().template cast();\n \n VectorXd g(y.size());\n // Forward differences on left and right edges\n g(0) = y(1) - y(0);\n g(N - 1) = y(N - 1) - y(N - 2);\n // Centered differences on interior points\n if (N > 2)\n {\n#pragma omp parallel for\n for (Index i = 1; i < N - 1; ++i)\n g(i) = (double) (y(i+1) - y(i-1)) / 2.0;\n }\n return g;\n}\n\ntemplate\nVectorXd Math::gradient(const DenseBase& x, const DenseBase& y)\n{\n if (x.size() != y.size())\n {\n std::stringstream s;\n s << __PRETTY_FUNCTION__ << \" ==> x and y must be of the same size.\" << std::endl;\n throw std::runtime_error(s.str());\n }\n\n if (y.rows() != 1 && y.cols() != 1)\n {\n std::stringstream s;\n s << __PRETTY_FUNCTION__ << \" ==> x and y must be row or column vectors/arrays.\" << std::endl;\n throw std::runtime_error(s.str());\n }\n\n const int N = y.size();\n if (N == 1)\n return y.derived().template cast();\n \n VectorXd g(y.size());\n // Forward differences on left and right edges\n g(0) = (y(1) - y(0)) / (x(1) - x(0));\n g(N - 1) = (y(N - 1) - y(N - 2)) / (x(N - 1) - x(N - 2));\n // Centered differences on interior points\n if (N > 2)\n {\n#pragma omp parallel for\n for (Index i = 1; i < N - 1; ++i)\n g(i) = (double) (y(i+1) - y(i-1)) / (x(i+1) - x(i-1));\n }\n return g;\n}\n\ntemplate\nstd::tuple Math::histogram(const DenseBase& x)\n{\n return Math::histogram(x, Edges::autorule(x, x.minCoeff(), x.maxCoeff(), false));\n}\n\ntemplate\nstd::tuple Math::histogram(const DenseBase& x, const VectorXd& edges)\n{\n if (x.size() < 3)\n {\n std::stringstream s;\n s << __PRETTY_FUNCTION__ << \" ==> x must have at least more than 3 elements.\" << std::endl;\n throw std::runtime_error(s.str());\n }\n\n if (!Math::isClose(std::abs(edges(1) - edges(0)), std::abs(edges(2) - edges(1))) ||\n !Math::isClose(std::abs(edges(2) - edges(1)), std::abs(edges(3) - edges(2))))\n {\n std::stringstream s;\n s << __PRETTY_FUNCTION__ << \" ==> Unsupported binwidth. function only prepared to deal with equal binwidths\" << std::endl;\n throw std::runtime_error(s.str());\n }\n\n const int numEqualBins = (int) edges.size() - 1;\n const double firstEdge = edges(0);\n const double lastEdge = edges(numEqualBins);\n const double norm = (double) numEqualBins / std::abs(lastEdge - firstEdge);\n VectorXi hist = VectorXi::Zero(numEqualBins);\n VectorXi bin(x.size());\n for (Index i = 0; i < x.size(); ++i)\n {\n if (x(i) < firstEdge || x(i) > lastEdge)\n continue;\n\n int pos = (int) (std::abs(x(i) - firstEdge) * norm);\n pos = pos == numEqualBins ? pos - 1 : pos;\n pos = x(i) < edges(pos) ? pos - 1 : pos;\n pos = (x(i) >= edges(pos + 1)) && (pos != (numEqualBins - 1)) ? pos + 1 : pos;\n hist(pos)++;\n bin(i) = pos;\n }\n\n return std::make_tuple(hist, edges, bin);\n}\n\ntemplate\nstd::tuple Math::cdf(const DenseBase& x)\n{\n return Math::cdf(x, Edges::autorule(x, x.minCoeff(), x.maxCoeff(), false));\n}\n\ntemplate\nstd::tuple Math::cdf(const DenseBase& x, const VectorXd& edges)\n{\n const auto H = Math::histogram(x, edges);\n const VectorXi hist = std::get<0>(H);\n const VectorXi bin = std::get<2>(H);\n \n VectorXd cum = VectorXd::Zero(hist.size());\n cum(0) = hist(0);\n for (Index i = 1; i < cum.size(); ++i)\n {\n cum(i) = (double) (cum(i-1) + hist(i));\n }\n\n const double sum = (double) hist.sum();\n#pragma omp parallel for\n for (Index i = 0; i < cum.size(); ++i)\n {\n cum(i) /= sum;\n }\n\n return std::make_tuple(cum, edges, bin);\n}\n\ntemplate\nVectorXd Math::conv1d(const DenseBase& x, const Kernel type, const int size, const double alpha)\n{\n VectorXd k(size);\n \n const int vOffset = (int) (size / 2);\n switch (type)\n {\n case Math::NORMAL:\n {\n const double N = (double) (size - 1) / 2.0;\n for (Index i = 0, j = -vOffset; i < size; ++i, ++j)\n k(i) = std::exp(-0.5 * ((alpha * j) / N) * ((alpha * j) / N));\n k = k / k.sum();\n }\n break;\n case Math::BOX:\n {\n for (Index i = 0; i < size; ++i)\n k(i) = 1.0 / size;\n }\n break;\n default:\n {\n const double N = ((double) size - 1.0) / 2.0;\n for (Index i = 0, j = -vOffset; i < size; ++i, ++j)\n k(i) = std::exp(-0.5 * ((alpha * j) / N) * ((alpha * j) / N));\n k = k / k.sum();\n }\n break;\n }\n return Math::conv1d(x, k);\n}\n\ntemplate\nVectorXd Math::conv1d(const DenseBase& x, const VectorXd& k)\n{\n if (x.rows() != 1 && x.cols() != 1)\n {\n std::stringstream s;\n s << __PRETTY_FUNCTION__ << \" ==> x must be a row or column vector/array.\" << std::endl;\n throw std::runtime_error(s.str());\n }\n\n if ((k.size() % 2) == 0)\n {\n std::stringstream s;\n s << __PRETTY_FUNCTION__ << \" ==> Kernel must have an odd number of elements.\" << std::endl;\n throw std::runtime_error(s.str());\n }\n \n if (k.sum() < 1.0 - MATH_EPS || k.sum() > 1.0 + MATH_EPS)\n {\n std::stringstream s;\n s << __PRETTY_FUNCTION__ << \"==> Kernel does not sum 1.\" << std::endl;\n throw std::runtime_error(s.str());\n }\n \n const int size = (int) k.size();\n const int offset = (int) (size / 2);\n \n VectorXd y(x.size() + (offset * 2));\n#pragma omp parallel for\n for (Index i = 0; i < x.size(); ++i)\n y(i + offset) = x(i);\n for (Index i = 0, j = offset; i < offset; ++i, --j)\n y(i) = x(j);\n for (Index i = y.size() - 1, j = x.size() - offset - 1; i >= y.size() - offset; --i, ++j)\n y(i) = x(j);\n\n VectorXd z(x.size());\n#pragma omp parallel for\n for (int i = 0; i < z.size(); ++i)\n z(i) = y.segment(i, size).transpose() * k;\n \n return z;\n}\n\ninline ArrayXd _pchipSlopes(const ArrayXd& h, const ArrayXd& delta)\n{\n assert(h.size() == delta.size());\n const int N = h.size();\n\n ArrayXi k(N);\n#pragma omp parallel for\n for (Index i = 0; i < N-1; ++i)\n k(i) = sign(delta(i))*sign(delta(i+1)) > 0 ? i : -1;\n\n ArrayXd hs(N);\n#pragma omp parallel for\n for (Index i = 0; i < N; ++i)\n {\n if (k(i) == -1)\n {\n hs(i) = 0;\n continue;\n }\n hs(i) = h(k(i)) + h(k(i)+1);\n }\n ArrayXd w1(N);\n ArrayXd w2(N);\n ArrayXd dmax(N);\n ArrayXd dmin(N);\n#pragma omp parallel for\n for (Index i = 0; i < N; ++i)\n {\n if (k(i) == -1)\n {\n w1(i) = 0.0;\n w2(i) = 0.0;\n dmin(i) = 0.0;\n dmax(i) = 0.0;\n continue;\n }\n w1(i) = (h(k(i)) + hs(i)) / (3.0 * hs(i));\n w2(i) = (h(k(i)+1) + hs(i)) / (3.0 * hs(i));\n dmax(i) = std::abs(delta(k(i)));\n dmin(i) = std::abs(delta(k(i)+1));\n if (dmax(i) < dmin(i))\n {\n dmin(i) = dmax(i);\n dmax(i) = std::abs(delta(k(i)+1));\n }\n }\n ArrayXd slopes(N+1);\n#pragma omp parallel for\n for (Index i = 0; i < N; ++i)\n {\n if (k(i) == -1)\n {\n slopes(i) = 0;\n continue;\n }\n slopes(k(i)+1) = dmin(i) / ((w1(i) * delta(k(i)) / dmax(i)) + (w2(i) * delta(k(i)+1) / dmax(i)));\n }\n slopes(0) = ((2.0 * h(0) + h(1)) * delta(0) - h(0) * delta(1)) / (h(0) + h(1));\n if (sign(slopes(0)) != sign(delta(0)))\n slopes(0) = 0;\n else if ((sign(delta(0)) != sign(delta(1))) && (std::abs(slopes(0)) > std::abs(3.0 * delta(0))))\n slopes(0) = 3.0 * delta(0);\n slopes(N) = ((2.0 * h(N-1) + h(N-2)) * delta(N-1) - h(N-1) * delta(N-2)) / (h(N-1) + h(N-2));\n if (sign(slopes(N)) != sign(delta(N-1)))\n slopes(N) = 0;\n else if ((sign(delta(N-1)) != sign(delta(N-2))) && (std::abs(slopes(N)) > std::abs(3.0 * delta(N-1))))\n slopes(N) = 3.0 * delta(N-1);\n\n return slopes;\n}\n\ninline ArrayXd _mAkimaSlopes(const ArrayXd& del)\n{\n const int N = del.size();\n \n const double delta_0 = 2.0 * del(0) - del(1);\n const double delta_m1 = 2.0 * delta_0 - del(0);\n const double delta_n = 2.0 * del(N-1) - del(N-2);\n const double delta_n1 = 2.0 * delta_n - del(N-1);\n\n ArrayXd delta(N+4);\n delta(0) = delta_m1;\n delta(1) = delta_0;\n delta.segment(2, N) = del;\n delta(N+2) = delta_n;\n delta(N+3) = delta_n1;\n\n const ArrayXd ddelta = Math::diff(delta);\n ArrayXd weights(N+3);\n#pragma omp parallel for\n for (Index i = 0; i < N+3; ++i)\n weights(i) = std::abs(ddelta(i)) + std::abs((delta(i) + delta(i+1)) / 2.0);\n\n ArrayXd slopes(N+1);\n#pragma omp parallel for\n for (Index i = 0; i < N+1; ++i)\n {\n const double w = weights(i) + weights(i+2);\n slopes(i) = w == 0 ? 0 : (delta(i+1) * weights(i+2) / w) + (delta(i+2) * weights(i) / w);\n }\n\n return slopes;\n}\n\ninline MatrixXd _pwch(const ArrayXd& x, const ArrayXd& y, const ArrayXd& slopes, const ArrayXd& h, const ArrayXd& delta)\n{\n const int N = x.size();\n\n ArrayXd dzzdx(N-1);\n ArrayXd dzdxdx(N-1);\n#pragma omp parallel for\n for (Index i = 0; i < N-1; ++i)\n {\n dzzdx(i) = (delta(i) - slopes(i)) / h(i);\n dzdxdx(i) = (slopes(i+1) - delta(i)) / h(i);\n }\n MatrixXd pp(N-1, 4);\n#pragma omp parallel for\n for (Index i = 0; i < N-1; ++i)\n {\n pp(i, 0) = (dzdxdx(i) - dzzdx(i)) / h(i);\n pp(i, 1) = 2.0 * dzzdx(i) - dzdxdx(i);\n pp(i, 2) = slopes(i);\n pp(i, 3) = y(i);\n }\n return pp;\n}\n\ninline ArrayXd _ppval(const MatrixXd& pp, const ArrayXd& x, const ArrayXd& xq)\n{\n const auto H = Math::histogram(xq, x);\n const VectorXi bin = std::get<2>(H);\n\n assert(bin.size() == xq.size());\n\n const int N = xq.size();\n ArrayXd xs(N);\n ArrayXd yq(N);\n#pragma omp parallel for\n for (Index i = 0; i < N; ++i)\n {\n xs(i) = xq(i) - x(bin(i));\n yq(i) = pp(bin(i), 0);\n }\n\n for (Index j = 1; j < 4; ++j)\n {\n#pragma omp parallel for\n for (Index i = 0; i < N; ++i)\n yq(i) = xs(i) * yq(i) + pp(bin(i), j);\n }\n return yq;\n}\n\n\ntemplate\nVectorXd Math::interp1(const DenseBase& x, const DenseBase& y, const DenseBase &xq, const Interpolation type)\n{\n if (x.size() != y.size())\n {\n std::stringstream s;\n s << __PRETTY_FUNCTION__ << \" ==> x and y must be of the same size.\" << std::endl;\n throw std::runtime_error(s.str());\n }\n\n if (x.size() < 3)\n {\n std::stringstream s;\n s << __PRETTY_FUNCTION__ << \" ==> x and y must have more than 2 elements.\" << std::endl;\n throw std::runtime_error(s.str());\n }\n\n if (xq.size() < 4)\n {\n std::stringstream s;\n s << __PRETTY_FUNCTION__ << \" ==> xq must have more than 3 elements.\" << std::endl;\n throw std::runtime_error(s.str());\n }\n\n const ArrayXd h = Math::diff(x);\n const ArrayXd delta = Math::diff(y).array() / h;\n const ArrayXd slopes = type == Math::PCHIP ? _pchipSlopes(h, delta) : _mAkimaSlopes(delta);\n \n return _ppval(_pwch(x, y, slopes, h, delta), x, xq);\n}\n\n/***************************** Implementation of Histogram Edges class *****************************/\n/***************************** must be here with the declaration first *****************************/\n\ntemplate\nVectorXd Edges::binpicker(const T minx, const T maxx, const double rawBinWidth)\n{\n const double xscale = (double) std::max(std::abs((double) minx), std::abs((double) maxx));\n const double xrange = (double) (maxx - minx);\n \n const double powOfTen = std::pow(10.0, std::floor(std::log10(rawBinWidth)));\n const double relSize = rawBinWidth / powOfTen;\n double binWidth;\n if (relSize < 1.5)\n binWidth = 1 * powOfTen;\n else if (relSize < 2.5)\n binWidth = 2 * powOfTen;\n else if (relSize < 4)\n binWidth = 3 * powOfTen;\n else if (relSize < 7.5)\n binWidth = 5 * powOfTen;\n else\n binWidth = 10 * powOfTen;\n \n const double leftEdge = std::min(binWidth * std::floor((double) minx / binWidth), (double) minx);\n const int nbinsActual = std::max(1, (int) std::ceil((double) (maxx - leftEdge) / binWidth));\n const double rightEdge = std::max(leftEdge + nbinsActual * binWidth, (double) maxx);\n \n VectorXd y(nbinsActual + 1);\n for (Index i = 0; i < nbinsActual; ++i)\n y(i) = leftEdge + ((double) i * binWidth);\n y(nbinsActual) = rightEdge;\n return y;\n}\n\ntemplate\nVectorXd Edges::autorule(const DenseBase& x, const typename Derived::Scalar minx, const typename Derived::Scalar maxx, const bool hardlimits)\n{\n const typename Derived::Scalar xrange = maxx - minx;\n if (x.size() > 0 && std::is_integral::value && xrange <= 50 && maxx <= (MATH_FLINTMAX / 2.0) && minx >= -(MATH_FLINTMAX / 2.0))\n return Edges::integerrule(x, minx, maxx, hardlimits);\n else\n return Edges::scottsrule(x, minx, maxx, hardlimits);\n}\n\ntemplate\nVectorXd Edges::scottsrule(const DenseBase& x, const typename Derived::Scalar minx, const typename Derived::Scalar maxx, const bool hardlimits)\n{\n const double sigma = Math::std(x);\n const double binwidth = 3.5 * sigma / std::pow((double) x.size(), 1.0 / 3.0);\n if (hardlimits)\n {\n const int nbins = (int) std::ceil((double) (maxx - minx) / binwidth);\n return Math::linspace(minx, maxx, nbins);\n }\n else\n {\n return Edges::binpicker(minx, maxx, binwidth);\n }\n}\n\ntemplate\nVectorXd Edges::integerrule(const DenseBase& x, const typename Derived::Scalar minx, const typename Derived::Scalar maxx, const bool hardlimits)\n{\n if (maxx > (MATH_FLINTMAX / 2.0) || minx < -(MATH_FLINTMAX / 2.0))\n {\n std::stringstream s;\n s << __PRETTY_FUNCTION__ << \" ==> Input out of integer range.\" << std::endl;\n throw std::runtime_error(s.str());\n }\n \n const int maximumBins = 65536;\n const typename Derived::Scalar xscale = x.derived().array().abs().maxCoeff();\n const typename Derived::Scalar xrange = x.maxCoeff() - x.minCoeff();\n \n double binwidth = 1;\n if (xrange > maximumBins)\n binwidth = std::pow(10.0, std::ceil(std::log10((double) xrange / (double) maximumBins)));\n \n if (hardlimits)\n {\n const double minxi = binwidth * std::ceil((double) minx / binwidth) + 0.5;\n const double maxxi = binwidth * std::floor((double) maxx / binwidth) - 0.5;\n const int N = (int) std::floor(((maxxi - minxi) / binwidth) + 3);\n VectorXd y(N);\n int j = 1;\n for (double i = minxi; i <= maxxi; i += binwidth)\n {\n y(j) = i;\n j++;\n }\n y(0) = minx;\n y(N-1) = maxx;\n return y;\n }\n else\n {\n const double minxi = std::floor(binwidth * round((double) minx / binwidth)) - 0.5 * binwidth;\n const double maxxi = std::ceil(binwidth * round((double) maxx / binwidth)) + 0.5 * binwidth;\n const int N = (int) std::floor(((maxxi - minxi) / binwidth) + 1);\n VectorXd y(N);\n int j = 0;\n for (double i = minxi; i <= maxxi; i += binwidth)\n {\n y(j) = i;\n j++;\n }\n return y;\n }\n}\n\ntemplate\nVectorXd Edges::sturgesrule(const DenseBase& x, const typename Derived::Scalar minx, const typename Derived::Scalar maxx, const bool hardlimits)\n{\n const int nbins = std::max(std::ceil(std::log2(x.size()) + 1), 1);\n if (hardlimits)\n {\n return Math::linspace(minx, maxx, nbins);\n }\n else\n {\n return Edges::binpicker(minx, maxx, (double)(maxx - minx) / (double) nbins);\n }\n}\n\ntemplate\nVectorXd Edges::sqrtrule(const DenseBase& x, const typename Derived::Scalar minx, const typename Derived::Scalar maxx, const bool hardlimits)\n{\n const int nbins = std::max(std::ceil(std::sqrt(x.size())), 1);\n if (hardlimits)\n {\n return Math::linspace(minx, maxx, nbins);\n }\n else\n {\n return Edges::binpicker(minx, maxx, (double)(maxx - minx) / (double) nbins);\n }\n}\n\n#endif", "meta": {"hexsha": "d9228667b8d0ae58d7cda93ed23dc03686c8a5d4", "size": 29844, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Math.hpp", "max_stars_repo_name": "javierjuan/tools", "max_stars_repo_head_hexsha": "fd51855d3babccabc2cf95e9d7ac00c0a390f7fc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Math.hpp", "max_issues_repo_name": "javierjuan/tools", "max_issues_repo_head_hexsha": "fd51855d3babccabc2cf95e9d7ac00c0a390f7fc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Math.hpp", "max_forks_repo_name": "javierjuan/tools", "max_forks_repo_head_hexsha": "fd51855d3babccabc2cf95e9d7ac00c0a390f7fc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4744287269, "max_line_length": 160, "alphanum_fraction": 0.5605146763, "num_tokens": 8649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810511092412, "lm_q2_score": 0.80563219364797, "lm_q1q2_score": 0.7632406744256576}} {"text": "#ifndef _RANDOM_DISCRIMINANT_\n#define _RANDOM_DISCRIMINANT_\n\n#include \n\n#include \n\nstruct DiscriminantModel {\n unsigned dim;\n Eigen::VectorXd projection_line;\n double decision_boundary;\n};\n\nvoid\nInitDiscriminantModel(\n DiscriminantModel* self,\n unsigned dimensionality,\n const Eigen::MatrixXd* class_0_data,\n const Eigen::MatrixXd* class_1_data) {\n/**\n *\n */\n self->dim = dimensionality;\n\n // get a random projection line (unit vector for easy projections)\n self->projection_line.resize(self->dim);\n unsigned i;\n for (i = 0; i < self->dim; ++i) {\n self->projection_line(i) = (double) (rand() % 100);\n }\n self->projection_line.normalize();\n\n Eigen::VectorXd class_0_projections = *class_0_data * self->projection_line;\n Eigen::VectorXd class_1_projections = *class_1_data * self->projection_line;\n\n double mu_0 = class_0_projections.mean();\n double mu_1 = class_1_projections.mean();\n double sigma_0 = 0.0;\n double sigma_1 = 0.0;\n for (i = 0; i < class_0_projections.size(); ++i) {\n sigma_0 += (class_0_projections(i) - mu_0) *\n (class_0_projections(i) - mu_0);\n sigma_1 += (class_1_projections(i) - mu_1) *\n (class_1_projections(i) - mu_1);\n }\n sigma_0 /= class_0_projections.size();\n sigma_1 /= class_1_projections.size();\n\n self->decision_boundary = 0.5 * (mu_1 - mu_0); // TODO: do actual boundary!!!!!!!!!!!\n}\n\n\nEigen::VectorXi\nGetDiscriminantPredictions(\n const DiscriminantModel* self,\n const Eigen::MatrixXd* observations) {\n/**\n *\n */\n Eigen::VectorXd projections = *observations * self->projection_line;\nstd::cout << projections << std::endl;\n\n Eigen::VectorXi predictions(projections.size());\n unsigned i;\n for (i = 0; i < predictions.size(); ++i) {\n predictions(i) = (projections(i) >= self->decision_boundary) ? 0 : 1;\n }\n\n return predictions;\n}\n\nvoid\nPrintDiscriminantModel(\n const DiscriminantModel* self,\n FILE* stream,\n const bool show_projection_line) {\n/**\n *\n */\n printf(\"Dimensionality: %u -> 1\\n\", self->dim);\n printf(\"Decision Boundary: %lf\\n\", self->decision_boundary);\n printf(\"Projection Line:\\n\");\n if (show_projection_line) {\n std::cout << self->projection_line << std::endl;\n }\n}\n\n#endif // define _RANDOM_DISCRIMINANT_", "meta": {"hexsha": "5f524cf82816a2f6efc743cba5b71575f4942ecd", "size": 2255, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "STAT775/HW07/HW07/HW07/random_discriminant.hpp", "max_stars_repo_name": "T-R0D/Past-Courses", "max_stars_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-03-13T17:32:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T16:51:22.000Z", "max_issues_repo_path": "STAT775/HW07/HW07/HW07/random_discriminant.hpp", "max_issues_repo_name": "T-R0D/Past-Courses", "max_issues_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-29T19:54:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-29T19:54:52.000Z", "max_forks_repo_path": "STAT775/HW07/HW07/HW07/random_discriminant.hpp", "max_forks_repo_name": "T-R0D/Past-Courses", "max_forks_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-10-18T03:31:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-29T13:23:10.000Z", "avg_line_length": 25.625, "max_line_length": 87, "alphanum_fraction": 0.6838137472, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7632223151165823}} {"text": "#include \n#include \nint main(int argc, char **argv) {\n using namespace std;\n \n // Solve the equation:\n // A*X = Y where:\n // A= 1.0 2.0\n // 4.0 9.0\n // \n // Y= 1\n // 3\n\n Eigen::VectorXd Y(2);\n Y(0)= 1.0;\n Y(1)= 3.0;\n Eigen::MatrixXd A(2,2);\n A(0,0)= 1.0; A(0,1)=2.0;\n A(1,0)= 4.0; A(1,1)=9.0;\n\n cout << \"Determinant = \" << A.determinant() << endl;\n\n Eigen::MatrixXd AInv= A.inverse();\n cout << \"Solution is \\n\" << AInv*Y << endl;\n\n}\n", "meta": {"hexsha": "e5ad46766831295b21283b67dfec8c2e79418fa6", "size": 486, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CH3/MATRIXSOLVE/src/matrixsolve.cpp", "max_stars_repo_name": "acastellanos95/AppCompPhys", "max_stars_repo_head_hexsha": "920a7ba707e92f1ef92fba9d97323863994f0b1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CH3/MATRIXSOLVE/src/matrixsolve.cpp", "max_issues_repo_name": "acastellanos95/AppCompPhys", "max_issues_repo_head_hexsha": "920a7ba707e92f1ef92fba9d97323863994f0b1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CH3/MATRIXSOLVE/src/matrixsolve.cpp", "max_forks_repo_name": "acastellanos95/AppCompPhys", "max_forks_repo_head_hexsha": "920a7ba707e92f1ef92fba9d97323863994f0b1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0, "max_line_length": 54, "alphanum_fraction": 0.5061728395, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9715639694252315, "lm_q2_score": 0.785308578375437, "lm_q1q2_score": 0.7629775196301251}} {"text": "#include \n#include \n#include \n#include \"linear_algebra_addon.hpp\"\nusing namespace Eigen;\nusing namespace std;\n\nMatrixXcd bl_bicgstab_rq(const MatrixXcd& A, const MatrixXcd& B, const double& tol, const int& itermax)\n{\n //Originally derived based on\n // Rashedi et al. 2016, On short recurrence Krylov type methods for linear systems with many right-hand sides, J. Comput. Appl. Math.\n // Guennouni et al 2003, A block version of BICGSTAB for linear systems with multiple right-hand sides, Electronic Transaction on Numerical Anaysis\n\n int N= B.rows();\n int L= B.cols();\n MatrixXcd thinQ(MatrixXcd::Identity(N,L));\n double Bnorm= B.norm();\n MatrixXcd X= MatrixXcd::Zero(N,L); // Initial guess of X (zeros)\n MatrixXcd R0= B-A*X;\n MatrixXcd R;\n MatrixXcd C;\n tie(R,C)= qr_reduced(R0);\n MatrixXcd Y0= R0;\n double norm0= R0.norm();\n double normr= norm0;\n MatrixXcd P= R;\n\n\n for(int k= 0; k < itermax; ++k){\n MatrixXcd AP= A*P;\n FullPivLU lu(Y0.adjoint()*AP);\n MatrixXcd alpha= lu.solve(Y0.adjoint()*R);\n MatrixXcd S= R-AP*alpha;\n MatrixXcd T= A*S;\n MatrixXcd SC= S*C;\n MatrixXcd TC= T*C;\n complex w= (SC.adjoint()*TC).trace()/(TC.adjoint()*TC).trace();\n X= X+P*alpha*C+w*SC;\n R= S-w*T;\n MatrixXcd U;\n tie(R,U)= qr_reduced(R);\n C= U*C;\n\n\n double err= C.norm()/Bnorm;\n cout << \"bl_bicgstab_rq: \" << \"iter= \" << k << \" relative err= \" << err << endl;\n if(err < tol) break;\n\n\n MatrixXcd beta= -lu.solve(Y0.adjoint()*T*U.inverse());\n P= R+(P-AP*w)*beta;\n\n\n }\n if((A*X-B).norm()/Bnorm > 10*tol){\n cerr << \"bl_bicgstab_rq did not converge to solution within error tolerance !\" << endl;\n // exit(EXIT_FAILURE);\n }\n\n return X;\n}\n", "meta": {"hexsha": "799a64539100dc5a9d352f3bda825883827a099d", "size": 1747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bl_bicgstab_rq.cpp", "max_stars_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_stars_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-27T08:44:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-27T08:44:06.000Z", "max_issues_repo_path": "bl_bicgstab_rq.cpp", "max_issues_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_issues_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bl_bicgstab_rq.cpp", "max_forks_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_forks_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1774193548, "max_line_length": 149, "alphanum_fraction": 0.6451058958, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317102, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7624680244853289}} {"text": "#include \n#include \nusing namespace std;\nint main() {\n Eigen::MatrixXf matrix = Eigen::MatrixXf::Random(3, 3);\n Eigen::MatrixXf matrix_c = Eigen::MatrixXf::Constant(3, 3, 2.f);\n Eigen::Vector3f vector(3), vector1(3);\n vector << 1, 2, 3;\n vector1 << 4, 5, 6;\n cout << \"初始矩阵=\\n\" << matrix << endl;\n cout << \"矩阵乘法(非elementwise)=\\n\" << matrix * matrix_c << \"\\n\";\n cout << \"矩阵和标量的乘法=\\n\" << matrix * 2.f << \"\\n\";\n cout << \"矩阵的转置=\\n\" << matrix.transpose() << \"\\n\";\n matrix.transposeInPlace();\n cout << \"矩阵的Inplace转置=\\n\" << matrix << \"\\n\";\n cout << \"矩阵和向量的乘法=\\n\" << matrix * vector << \"\\n\";\n cout << \"矩阵的reduce操作\\n\";\n cout << \"所有元素求和=\" << matrix.sum() << \"\\n\";\n cout << \"矩阵的元素累乘=\" << matrix.prod() << \"\\n\";\n cout << \"矩阵的均值=\" << matrix.mean() << \"\\n\";\n cout << \"矩阵的最小元素=\" << matrix.minCoeff() << \"\\n\";\n cout << \"矩阵的最大元素=\" << matrix.maxCoeff() << \"\\n\";\n cout << \"矩阵的迹=\" << matrix.trace() << \"\\n\";\n\n cout << \"向量的点乘=\\n\" << vector.dot(vector1) << endl;\n cout << \"向量的叉乘(只支持三维向量)=\\n\" << vector.cross(vector1) << endl;\n}\n", "meta": {"hexsha": "1f474f14871cc36e7358e4e64531bccddf2f4048", "size": 1049, "ext": "cc", "lang": "C++", "max_stars_repo_path": "code/matrix_demo2.cc", "max_stars_repo_name": "bleedingfight/eigen-docs", "max_stars_repo_head_hexsha": "c74d91e935eb0afbb2fc1ed6f191b9817ad2b424", "max_stars_repo_licenses": ["LPPL-1.3c"], "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/matrix_demo2.cc", "max_issues_repo_name": "bleedingfight/eigen-docs", "max_issues_repo_head_hexsha": "c74d91e935eb0afbb2fc1ed6f191b9817ad2b424", "max_issues_repo_licenses": ["LPPL-1.3c"], "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/matrix_demo2.cc", "max_forks_repo_name": "bleedingfight/eigen-docs", "max_forks_repo_head_hexsha": "c74d91e935eb0afbb2fc1ed6f191b9817ad2b424", "max_forks_repo_licenses": ["LPPL-1.3c"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4642857143, "max_line_length": 66, "alphanum_fraction": 0.5557673975, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632316144274, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7621492811699266}} {"text": "/**\n * @file engquistoshernumericalflux.cc\n * @brief NPDE homework \"EngquistOsherNumericalFlux\" code\n * @author Oliver Rietmann\n * @date 23.04.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"engquistoshernumericalflux.h\"\n\n#include \n#include \n#include \n\nnamespace EngquistOsherNumericalFlux {\n\n/* SAM_LISTING_BEGIN_1 */\ndouble EngquistOsherNumFlux(double v, double w) {\n double result;\n#if SOLUTION\n auto Fv = [](double v) { return 0 <= v ? std::cosh(v) - 0.5 : 0.5; };\n result = Fv(v) + Fv(-w);\n#else\n //====================\n // Your code goes here\n //====================\n#endif\n return result;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\nEigen::VectorXd solveCP(double a, double b, Eigen::VectorXd u0, double T) {\n // Find the maximal speed of propagation\n double A = u0.minCoeff();\n double B = u0.maxCoeff();\n double K = std::max(std::abs(std::sinh(A)), std::abs(std::sinh(B)));\n // Set uniform timestep according to CFL condition\n int N = u0.size();\n double h = (b - a) / N;\n double tau_max = h / K;\n double timesteps = std::ceil(T / tau_max);\n double tau = T / timesteps;\n\n // Main timestepping loop\n#if SOLUTION\n Eigen::VectorXd mu(N);\n for (int i = 0; i < timesteps; ++i) {\n mu.swap(u0);\n double F_minus;\n double F_plus = EngquistOsherNumFlux(mu(0), mu(0));\n for (int j = 0; j < N - 1; ++j) {\n F_minus = F_plus;\n F_plus = EngquistOsherNumFlux(mu(j), mu(j + 1));\n u0(j) = mu(j) - tau / h * (F_plus - F_minus);\n }\n F_minus = F_plus;\n F_plus = EngquistOsherNumFlux(mu(N - 1), mu(N - 1));\n u0(N - 1) = mu(N - 1) - tau / h * (F_plus - F_minus);\n }\n#else\n //====================\n // Your code goes here\n //====================\n#endif\n\n return u0;\n}\n/* SAM_LISTING_END_2 */\n\n} // namespace EngquistOsherNumericalFlux\n", "meta": {"hexsha": "3704276262dbea7806901ff01d7ab2e32c5d9a8a", "size": 1831, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/EngquistOsherNumericalFlux/mastersolution/engquistoshernumericalflux.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/EngquistOsherNumericalFlux/mastersolution/engquistoshernumericalflux.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/EngquistOsherNumericalFlux/mastersolution/engquistoshernumericalflux.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 25.4305555556, "max_line_length": 75, "alphanum_fraction": 0.6018569088, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8652240895276223, "lm_q1q2_score": 0.7620868444373399}} {"text": "/**\n* gaussian.hpp\n* @author : koide\n* 13/06/12\n* 13/06/20 add GMM\n* 13/08/03 rename\n* 13/11/16 add univariate gauss distibution and univariate gaussian mixture\n* 14/10/13 add KL divergence\n* 14/10/16 add univariate L2 distance\n* 14/11/11 IncrementalGaussianDistribution\n* 15/02/13 make IncrementalGaussianDistribution faster using PartialPivLu\n* 15/08/20 GaussianEstimater, IndependentGaussianEstimater\n**/\n#ifndef KKL_GAUSSIAN_HPP\n#define KKL_GAUSSIAN_HPP\n\n//#define _USE_BOOST_ERF\n\n#define _USE_MATH_DEFINES\n#include \n#include \n#include \n#include \n\n#ifdef _USE_BOOST_ERF\n#include \n#endif\n\nnamespace kkl{\n\tnamespace math{\n\n /**\n * @brief univariate gaussian PDF\n */\n\t\ttemplate\n\t\tT gaussianProbUni(T mean, T var, T x){\n\t\t\tconst T dif = x - mean;\n\t\t\treturn 1.0 / sqrt(2.0 * M_PI * var) * exp(-(dif * dif) / (2 * var));\n\t\t}\n\n /**\n * @brief multivariate gaussian PDF\n */\n\t\ttemplate\n\t\tT gaussianProbMul(const Eigen::Matrix& mean, const Eigen::Matrix& cov, const Eigen::Matrix& x) {\n\t\t\tconst T sqrtDet = sqrt(cov.determinant());\n\t\t\tconst Eigen::Matrix dif = x - mean;\n\t\t\tconst T lhs = 1.0 / (pow(2.0 * M_PI, p / 2.0) * sqrtDet);\n\t\t\tconst T rhs = exp(-0.5 * ((dif.transpose() * cov.inverse() * dif))(0, 0));\n\t\t\treturn lhs * rhs;\n\t\t}\n\n#ifdef _USE_BOOST_ERF\n /**\n * @brief univariate cumulative probability function\n */\n\t\ttemplate\n\t\tT gaussianCumulativeProbUni(T mean, T var, T x) {\n\t\t\treturn 0.5 * (1 + boost::math::erf((x - mean) / sqrt(2 * var)));\n\t\t};\n#endif\n\n /**\n * @brief compute an error ellipse\n */\n template\n Eigen::Matrix errorEllipse(const Matrix& cov, double kai) {\n Eigen::SelfAdjointEigenSolver> solver(cov);\n\n Eigen::Matrix params;\n params[0] = std::sqrt(kai * kai * solver.eigenvalues()[1]);\n params[1] = std::sqrt(kai * kai * solver.eigenvalues()[0]);\n params[2] = std::atan2(solver.eigenvectors()(0, 2), solver.eigenvectors()(1, 2));\n\n return params;\n }\n\n /**\n * @brief squared mahalanobis distance\n */\n\t\ttemplate\n\t\tT squaredMahalanobisDistance(const Eigen::Matrix& mean, const Eigen::Matrix& cov, const Eigen::Matrix& x){\n\t\t\tconst Eigen::Matrix diff = x - mean;\n\t\t\tdouble distance = diff.transpose() * cov.inverse() * diff;\n\t\t\treturn distance;\n\t\t}\n\n /**\n * @brief univariate squared mahalanobis distance\n */\n\t\ttemplate\n\t\tT squaredMahalanobisDistanceUni(T mean, T var, T x) {\n\t\t\tT diff = mean - x;\n\t\t\treturn diff * diff / var;\n\t\t}\n\n }\n}\n\n#endif\n", "meta": {"hexsha": "db441bb3fe67bd8b2ddd181df5d40ac0a0f9ae84", "size": 2762, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kkl/math/gaussian.hpp", "max_stars_repo_name": "y-lai/hdl_people_tracking", "max_stars_repo_head_hexsha": "fb7ec799047b8ea833a175abd2599793b8966c24", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 207.0, "max_stars_repo_stars_event_min_datetime": "2018-03-10T14:56:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T07:32:53.000Z", "max_issues_repo_path": "include/kkl/math/gaussian.hpp", "max_issues_repo_name": "y-lai/hdl_people_tracking", "max_issues_repo_head_hexsha": "fb7ec799047b8ea833a175abd2599793b8966c24", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2018-02-19T10:50:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T19:44:55.000Z", "max_forks_repo_path": "include/kkl/math/gaussian.hpp", "max_forks_repo_name": "y-lai/hdl_people_tracking", "max_forks_repo_head_hexsha": "fb7ec799047b8ea833a175abd2599793b8966c24", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 91.0, "max_forks_repo_forks_event_min_datetime": "2018-02-23T09:44:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T01:38:14.000Z", "avg_line_length": 27.3465346535, "max_line_length": 135, "alphanum_fraction": 0.6433743664, "num_tokens": 876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.942506726044381, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7616087882258553}} {"text": "\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// Copyright Paul A. Bristow 2015.\r\n// Copyright Christopher Kormanyos 2015.\r\n\r\n// This file is written to be included from a Quickbook .qbk document.\r\n// It can be compiled by the C++ compiler, and run. Any output can\r\n// also be added here as comment or included or pasted in elsewhere.\r\n// Caution: this file contains Quickbook markup as well as code\r\n// and comments: don't change any of the special comment markups!\r\n\r\n// This file also includes Doxygen-style documentation about the function of the code.\r\n// See http://www.doxygen.org for details.\r\n\r\n//! \\file\r\n\r\n//! \\brief Example program showing a polynomial approximation of sin(negatable).\r\n\r\n// Below are snippets of code that are included into Quickbook file fixed_point.qbk.\r\n\r\n#include \r\n#include \r\n\r\n#include \r\n\r\nnamespace local\r\n{\r\n template\r\n NumericType sin(const NumericType& x)\r\n {\r\n // This subroutine computes sin(x) using an order 5 polynomial\r\n // approximation that achieves about 4 decimal digits of precision\r\n // in the range -pi/2 < x < +pi/2.\r\n\r\n // The coefficients in the polynomial approximation originate\r\n // from C. Kormanyos, Real-Time C++ (Springer, Heidelberg, 2013).\r\n // See Sect. 13.3, in particular Eqs. 13.4 and 13.5 therein.\r\n\r\n // Use the scaled argument chi = x / (pi/2).\r\n const NumericType chi = (x * 2) / NumericType(3.14159265358979323846F);\r\n\r\n // Compute chi^2, as this is also used in the polynomial approximation.\r\n const NumericType chi2 = chi * chi;\r\n\r\n // Perform the polynomial approximation using a coefficient\r\n // expansion via the method of Horner.\r\n return (( 0.0722739F\r\n * chi2 - 0.6425639F)\r\n * chi2 + 1.5704128F)\r\n * chi;\r\n }\r\n}\r\n\r\nint main()\r\n{\r\n // This example computes approximations of sin(x) in the\r\n // range -pi/2 < x < pi/2. Comparison are made between\r\n // fixed-point calculations and floating-point calculations.\r\n // A 16-bit fixed-point type is used, as may be well-suited\r\n // for a tiny bare-metal embedded system.\r\n\r\n // The arguments used in the comparisons are:\r\n // x = (approx.) 1/4, 1/2, 3/4, 1, 5/4, 3/2.\r\n\r\n // Here we compute sin(n/4) for 1 <= n < 7 for\r\n // a fixed-point negatable type.\r\n std::cout << \"fixed-point: \";\r\n for(int n = 1; n < 7; ++n)\r\n {\r\n typedef boost::fixed_point::negatable<5, -10> fixed_point_type;\r\n\r\n const fixed_point_type x = fixed_point_type(n) / 4;\r\n\r\n std::cout << std::setprecision(4)\r\n << std::fixed\r\n << local::sin(x)\r\n << \" \";\r\n }\r\n std::cout << std::endl;\r\n\r\n // Compare with the control values of sin(n/4)\r\n // computed with a built-in floating-point type.\r\n std::cout << \"float-point: \";\r\n for(int n = 1; n < 7; ++n)\r\n {\r\n using std::sin;\r\n\r\n const float x = float(n) / 4;\r\n\r\n std::cout << std::setprecision(4)\r\n << std::fixed\r\n << sin(x)\r\n << \" \";\r\n }\r\n std::cout << std::endl;\r\n}\r\n", "meta": {"hexsha": "503052ad3bee460ba4d465f6cda46208b2b214f2", "size": 3251, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fixed_point_polynomial_approx_sin.cpp", "max_stars_repo_name": "BoostGSoC15/fixed-point", "max_stars_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/fixed_point_polynomial_approx_sin.cpp", "max_issues_repo_name": "BoostGSoC15/fixed-point", "max_issues_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/fixed_point_polynomial_approx_sin.cpp", "max_forks_repo_name": "BoostGSoC15/fixed-point", "max_forks_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1881188119, "max_line_length": 87, "alphanum_fraction": 0.6271916333, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422644, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7615580283709034}} {"text": "// Exercise 5.1.5 - Statistical Functions\r\n//\r\n// by Scott Sidoli\r\n//\r\n// 5-30-19\r\n//\r\n// Main.cpp\r\n//\r\n// In this exercise, we modify the code in TestNormalDistribution.cpp to work with the exponential distribution instead of the \r\n// normal distribution and the poisson distribution instead of the gamma distribution.\r\n\r\n#include \r\n#include \r\n#include // For non-member functions of distributions\r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\nusing namespace std;\r\n\r\n\r\nint main()\r\n{\r\n\t// Don't forget to tell compiler which namespace\r\n\tusing namespace boost::math;\r\n\r\n\t//=============================== Normal Distribution ===============================\r\n\r\n\tnormal_distribution<> myNormal(1.0, 10.0); // Default type is 'double'\r\n\tcout << \"Mean: \" << mean(myNormal) << \", standard deviation: \" << standard_deviation(myNormal) << endl;\r\n\r\n\t// Distributional properties\r\n\tdouble x = 10.25;\r\n\r\n\tcout << \"pdf: \" << pdf(myNormal, x) << endl;\r\n\tcout << \"cdf: \" << cdf(myNormal, x) << endl;\r\n\r\n\t// Choose another data type and now a N(0,1) variate\r\n\tnormal_distribution myNormal2;\r\n\tcout << \"Mean: \" << mean(myNormal2) << \", standard deviation: \" << standard_deviation(myNormal2) << endl;\r\n\r\n\tcout << \"pdf: \" << pdf(myNormal2, x) << endl;\r\n\tcout << \"cdf: \" << cdf(myNormal2, x) << endl;\r\n\r\n\t// Choose precision\r\n\tcout.precision(10); // Number of values behind the comma\r\n\r\n\t// Other properties\r\n\tcout << \"\\n***normal distribution: \\n\";\r\n\tcout << \"mean: \" << mean(myNormal) << endl;\r\n\tcout << \"variance: \" << variance(myNormal) << endl;\r\n\tcout << \"median: \" << median(myNormal) << endl;\r\n\tcout << \"mode: \" << mode(myNormal) << endl;\r\n\tcout << \"kurtosis excess: \" << kurtosis_excess(myNormal) << endl;\r\n\tcout << \"kurtosis: \" << kurtosis(myNormal) << endl;\r\n\tcout << \"characteristic function: \" << chf(myNormal, x) << endl;\r\n\tcout << \"hazard: \" << hazard(myNormal, x) << endl;\r\n\r\n\t//=============================== Exponential Distribution ===============================\r\n\r\n\tdouble scaleParameter = 0.5;\r\n\r\n\t// Default type is 'double'\r\n\texponential_distribution<> myExponential(scaleParameter);\r\n\r\n\tcout << \"Mean: \" << mean(myExponential) << \", standard deviation: \" << standard_deviation(myExponential) << endl;\r\n\r\n\t// PDF and CDF\r\n\tcout << \"pdf: \" << pdf(myExponential, x) << endl;\r\n\tcout << \"cdf: \" << cdf(myExponential, x) << endl;\r\n\r\n\t// Using another data type and a N(0,1) variate\r\n\texponential_distribution myExponential2(1.0);\r\n\tcout << \"Mean: \" << mean(myExponential2) << \", standard deviation: \" << standard_deviation(myExponential2) << endl;\r\n\r\n\t// PDF and CDF\r\n\tcout << \"pdf: \" << pdf(myExponential2, x) << endl;\r\n\tcout << \"cdf: \" << cdf(myExponential2, x) << endl;\r\n\r\n\t// Other properties\r\n\tcout << \"\\n***exponential distribution: \\n\";\r\n\tcout << \"mean: \" << mean(myExponential) << endl;\r\n\tcout << \"variance: \" << variance(myExponential) << endl;\r\n\tcout << \"median: \" << median(myExponential) << endl;\r\n\tcout << \"mode: \" << mode(myExponential) << endl;\r\n\tcout << \"kurtosis excess: \" << kurtosis_excess(myExponential) << endl;\r\n\tcout << \"kurtosis: \" << kurtosis(myExponential) << endl;\r\n\tcout << \"characteristic function: \" << chf(myExponential, x) << endl;\r\n\tcout << \"hazard: \" << hazard(myExponential, x) << endl;\r\n\r\n\t//=============================== Gamma Distribution ===============================\r\n\tdouble alpha = 3.0; // Shape parameter, k\r\n\tdouble beta = 0.5;\t// Scale parameter, theta\r\n\tgamma_distribution myGamma(alpha, beta);\r\n\tcout << \"everything that follows is for the gamma distribution\" << endl;\r\n\tdouble val = 13.0;\r\n\tcout << endl << \"pdf: \" << pdf(myGamma, val) << endl;\r\n\tcout << \"cdf: \" << cdf(myGamma, val) << endl;\r\n\r\n\tvector pdfList;\r\n\tvector cdfList;\r\n\r\n\tdouble start = 0.0;\r\n\tdouble end = 10.0;\r\n\tlong N = 30;\t\t// Number of subdivisions\r\n\r\n\tval = 0.0;\r\n\tdouble h = (end - start) / double(N);\r\n\r\n\tfor (long j = 1; j <= N; ++j)\r\n\t{\r\n\t\tpdfList.push_back(pdf(myGamma, val));\r\n\t\tcdfList.push_back(cdf(myGamma, val));\r\n\r\n\t\tval += h;\r\n\t}\r\n\r\n\tfor (long j = 0; j < pdfList.size(); ++j)\r\n\t{\r\n\t\tcout << pdfList[j] << \", \" << endl;\r\n\r\n\t}\r\n\r\n\tcout << \"***\" << endl;\r\n\r\n\tfor (long j = 0; j < cdfList.size(); ++j)\r\n\t{\r\n\t\tcout << cdfList[j] << \", \" << endl;\r\n\r\n\t}\r\n\r\n\t//=============================== Poisson Distribution ===============================\r\n\tcout << \"everything that follows is for the Poisson distribution\" << endl;\r\n\tdouble mean = 3.0;\r\n\tpoisson_distribution myPoisson(mean);\r\n\r\n\tval = 3.5;\r\n\tcout << \"pdf: \" << pdf(myPoisson, val) << endl;\r\n\tcout << \"cdf: \" << cdf(myPoisson, val) << endl;\r\n\r\n\tvector pdfList2;\r\n\tvector cdfList2;\r\n\r\n\tdouble start2 = 0.0;\r\n\tdouble end2 = 6.0;\r\n\tlong N2 = 30;\t\t// Number of subdivisions\r\n\r\n\tval = 0.0;\r\n\tdouble h2 = (end2 - start2) / double(N2);\r\n\r\n\tfor (long j = 1; j <= N2; ++j)\r\n\t{\r\n\t\tpdfList2.push_back(pdf(myPoisson, val));\r\n\t\tcdfList2.push_back(cdf(myPoisson, val));\r\n\r\n\t\tval += h2;\r\n\t}\r\n\r\n\tfor (long j = 0; j < pdfList2.size(); ++j)\r\n\t{\r\n\t\tcout << pdfList2[j] << \", \"<< endl;\r\n\r\n\t}\r\n\r\n\tcout << \"***\" << endl;\r\n\r\n\tfor (long j = 0; j < cdfList2.size(); ++j)\r\n\t{\r\n\t\tcout << cdfList[j] << \", \" << endl;\r\n\r\n\t}\r\n\treturn 0;\r\n}", "meta": {"hexsha": "443417988f2437355b72565cbd99f68f4290a61e", "size": 5359, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Scott_Sidoli Level 8 HW Submission/Section 5.1/Exercise515/Exercise515/Main.cpp", "max_stars_repo_name": "scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate", "max_stars_repo_head_hexsha": "79c2fb297a85c914d5f0b8671bb17636801e3ce7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-05T08:14:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T08:14:37.000Z", "max_issues_repo_path": "Scott_Sidoli Level 8 HW Submission/Section 5.1/Exercise515/Exercise515/Main.cpp", "max_issues_repo_name": "scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate", "max_issues_repo_head_hexsha": "79c2fb297a85c914d5f0b8671bb17636801e3ce7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Scott_Sidoli Level 8 HW Submission/Section 5.1/Exercise515/Exercise515/Main.cpp", "max_forks_repo_name": "scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate", "max_forks_repo_head_hexsha": "79c2fb297a85c914d5f0b8671bb17636801e3ce7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7988505747, "max_line_length": 128, "alphanum_fraction": 0.5864900168, "num_tokens": 1491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7615399784796634}} {"text": "#include \"utils.h\"\n#include \"bshelper.h\"\n#include \n#include \n\nusing boost::math::normal;\n\nconst double getD1(double asset_price, double strike, double rate, double volatility, double time_to_maturity) {\n double unadjusted_d1 = log(asset_price / strike) + (rate + pow(volatility, 2) / 2) * time_to_maturity;\n double result = unadjusted_d1 / (volatility * sqrt(time_to_maturity));\n return result;\n}\n\nconst double getD2(double asset_price, double strike, double rate, double volatility, double time_to_maturity) {\n double unadjusted_d2 = log(asset_price / strike) + (rate - pow(volatility, 2) / 2) * time_to_maturity;\n double result = unadjusted_d2 / (volatility * sqrt(time_to_maturity));\n return result;\n}\n\nconst double weightAsset(double asset_price, double option_d1) {\n normal normalDistInstance;\n double d1_probability = cdf(normalDistInstance, option_d1);\n return asset_price * d1_probability;\n}\n\nconst double weightStrike(double option_strike, double option_d2, double rate, double time_to_maturity) {\n normal normalDistInstance;\n double d2_probability = cdf(normalDistInstance, option_d2);\n double discount_factor = continuous_discount_factor(rate, time_to_maturity);\n return option_strike * discount_factor * d2_probability;\n}\n\n\nconst double\nevaluateCall(double option_strike, double time_to_maturity, double rate, double volatility, double asset_price) {\n double d1_value = getD1(asset_price, option_strike, rate, volatility, time_to_maturity);\n double d2_value = getD2(asset_price, option_strike, rate, volatility, time_to_maturity);\n\n double weighted_asset = weightAsset(asset_price, d1_value);\n double weighted_strike = weightStrike(option_strike, d2_value, rate, time_to_maturity);\n\n return weighted_asset - weighted_strike;\n}\n\nconst double\nevaluatePut(double option_strike, double time_to_maturity, double rate, double volatility, double asset_price) {\n double d1_value = getD1(asset_price, option_strike, rate, volatility, time_to_maturity);\n double d2_value = getD2(asset_price, option_strike, rate, volatility, time_to_maturity);\n\n double weighted_asset = weightAsset(asset_price, -d1_value);\n double weighted_strike = weightStrike(option_strike, -d2_value, rate, time_to_maturity);\n\n return weighted_strike - weighted_asset;\n}\n\nconst double\nblackScholes(enum OptionType option_type, double option_strike, double time_to_maturity, double rate, double volatility,\n double asset_price) {\n switch (option_type) {\n case call:\n return evaluateCall(option_strike, time_to_maturity, rate, volatility, asset_price);\n case put:\n return evaluatePut(option_strike, time_to_maturity, rate, volatility, asset_price);\n }\n return 0;\n}", "meta": {"hexsha": "2cdce41036c6cf39e61f0f948a8b36f0e13d54d1", "size": 2805, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "assignment/src/Utils/bshelper.cpp", "max_stars_repo_name": "paulochang/finance_valuator_extended", "max_stars_repo_head_hexsha": "1c9f638d0b1dd888b4a1010c47c4e1999ed6f5bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assignment/src/Utils/bshelper.cpp", "max_issues_repo_name": "paulochang/finance_valuator_extended", "max_issues_repo_head_hexsha": "1c9f638d0b1dd888b4a1010c47c4e1999ed6f5bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment/src/Utils/bshelper.cpp", "max_forks_repo_name": "paulochang/finance_valuator_extended", "max_forks_repo_head_hexsha": "1c9f638d0b1dd888b4a1010c47c4e1999ed6f5bc", "max_forks_repo_licenses": ["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.5, "max_line_length": 120, "alphanum_fraction": 0.7632798574, "num_tokens": 652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661002182845, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7614431367654685}} {"text": "#include \n#include \n#include \n#include \n#include \n\nusing Eigen::AngleAxisf;\nusing Eigen::Matrix3f;\nusing Eigen::Vector3f;\nusing Eigen::Quaternionf;\nusing Eigen::Transform;\n\nint main()\n{\n const float angle_x = 30.0f * M_PI / 180.0f;\n const float angle_y = 20.0f * M_PI / 180.0f;\n const float angle_z = 10.0f * M_PI / 180.0f;\n const Vector3f target(1, 2, 3);\n const Vector3f bias(3, 2, 1);\n Matrix3f fix_axis_m;\n Matrix3f unfix_axis_m;\n std::ofstream file;\n\n file.open(\"transform_wcm.txt\");\n\n // 计算固定坐标系下的旋转矩阵\n {\n // Eigen 自带的轴角表示系统,传入坐标轴和旋转角度即可\n // 由于 AngleAxisf 重载了乘法运算,所以合并多个旋转矩阵只要用乘法就行\n // http://eigen.tuxfamily.org/dox/classEigen_1_1AngleAxis.html\n Matrix3f m = AngleAxisf(angle_z, Vector3f::UnitZ())\n * AngleAxisf(angle_y, Vector3f::UnitY())\n * AngleAxisf(angle_x, Vector3f::UnitX()).toRotationMatrix();\n\n std::cout << \"\\n固定坐标系下的旋转矩阵:\" << std::endl\n << m << std::endl;\n fix_axis_m = m;\n\n AngleAxisf res;\n // 从旋转矩阵中得到轴角表示\n // http://eigen.tuxfamily.org/dox/classEigen_1_1AngleAxis.html#a2e35689645f69ba886df1a0a14b76ffe\n res.fromRotationMatrix(fix_axis_m);\n file << \"固定坐标系:\" << std::endl\n << \"旋转轴:(\" << res.axis().transpose() << \"), 旋转角\" << res.angle() * 180.0f / M_PI << std::endl\n << \"四元数表示:[\" << Quaternionf(res).vec().transpose() << \"]\" << std::endl;\n }\n\n // 计算不固定坐标系下的旋转矩阵\n {\n Vector3f axis_x = Vector3f::UnitX();\n Vector3f axis_y = Vector3f::UnitY();\n Vector3f axis_z = Vector3f::UnitZ();\n Matrix3f m = Matrix3f::Identity();\n\n // 这里的 lambda 函数对三个坐标轴都进行了旋转\n // 注意函数的捕获列表,& 表示捕获作用域内所有变量的引用\n // 所以在函数内我们可以直接修改函数外变量的值\n auto rotate_axises = [&](const AngleAxisf rotate) {\n axis_x = rotate * axis_x;\n axis_y = rotate * axis_y;\n axis_z = rotate * axis_z;\n m = rotate * m;\n };\n\n // 从 x 开始旋转\n rotate_axises(AngleAxisf(angle_x, axis_x));\n rotate_axises(AngleAxisf(angle_y, axis_y));\n rotate_axises(AngleAxisf(angle_z, axis_z));\n\n std::cout << \"\\n不固定坐标系下的旋转矩阵:\" << std::endl\n << m << std::endl;\n unfix_axis_m = m;\n\n AngleAxisf res;\n res.fromRotationMatrix(unfix_axis_m);\n file << \"\\n不固定坐标系:\" << std::endl\n << \"旋转轴:(\" << res.axis().transpose() << \"), 旋转角\" << res.angle() * 180.0f / M_PI << std::endl\n << \"四元数表示:[\" << Quaternionf(res).vec().transpose() << \"]\" << std::endl;\n }\n\n // 计算向量的齐次变换\n {\n // 使用 Transform 表示齐次变换\n // http://eigen.tuxfamily.org/dox/group__TutorialGeometry.html#title2\n Transform t;\n t = AngleAxisf(angle_z, Vector3f::UnitZ());\n // 等价于 t = t * AngleAxisf(angle_y, Vector3f::UnitY())\n t.rotate(AngleAxisf(angle_y, Vector3f::UnitY())); \n t.rotate(AngleAxisf(angle_x, Vector3f::UnitX()));\n // 等价于 t = t*() + bias\n // 括号表示要旋转的向量\n t.pretranslate(bias);\n std::cout << std::endl << t.matrix() << std::endl;\n\n std::cout << \"\\n固定坐标下,齐次变换目标向量结果为:\" << std::endl\n << t*target << std::endl;\n\n file << \"\\n固定坐标下,齐次变换目标向量结果为:(\"\n << (t * target).transpose() << \")\" << std::endl;\n\n // 从旋转矩阵构造四元数\n // http://eigen.tuxfamily.org/dox/classEigen_1_1QuaternionBase.html#title30\n Quaternionf q(unfix_axis_m);\n std::cout << \"\\n不固定坐标系下,齐次变换目标向量结果为:\" << std::endl\n << (q.toRotationMatrix()*target) + bias << std::endl;\n\n file << \"\\n不固定坐标下,齐次变换目标向量结果为:(\"\n << ((q.toRotationMatrix() * target) + bias).transpose() << \")\" << std::endl;\n }\n file.close();\n\n // 手搓一个固定坐标系下的旋转矩阵,证明 Eigen 库的正确性\n {\n using std::sin;\n using std::cos;\n Matrix3f m = Matrix3f::Identity();\n Matrix3f tmp;\n\n // 绕 x 轴旋转\n tmp << 1, 0, 0,\n 0, cos(angle_x), -sin(angle_x),\n 0, sin(angle_x), cos(angle_x);\n m = tmp * m;\n\n // 绕 y 轴旋转\n tmp << cos(angle_y), 0, sin(angle_y),\n 0, 1, 0,\n -sin(angle_y), 0, cos(angle_y);\n m = tmp * m;\n\n // 绕 z 轴旋转\n tmp << cos(angle_z), -sin(angle_z), 0,\n sin(angle_z), cos(angle_z), 0,\n 0, 0, 1;\n m = tmp*m;\n std::cout << std::endl << m*target + bias << std::endl;\n }\n\n return 0;\n}", "meta": {"hexsha": "fd20be5dd4857bf1a65bae15819ef15444931a6b", "size": 4511, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CH3-Transform/transform/src/main.cpp", "max_stars_repo_name": "HopeCollector/SLAMResearch", "max_stars_repo_head_hexsha": "747f26a68c072af00567f8009083fd46550fc56b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-14T07:53:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-14T07:58:04.000Z", "max_issues_repo_path": "CH3-Transform/transform/src/main.cpp", "max_issues_repo_name": "HopeCollector/SLAMResearch", "max_issues_repo_head_hexsha": "747f26a68c072af00567f8009083fd46550fc56b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CH3-Transform/transform/src/main.cpp", "max_forks_repo_name": "HopeCollector/SLAMResearch", "max_forks_repo_head_hexsha": "747f26a68c072af00567f8009083fd46550fc56b", "max_forks_repo_licenses": ["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.2214285714, "max_line_length": 105, "alphanum_fraction": 0.5473287519, "num_tokens": 1678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7613891268872125}} {"text": "#include \n#include \n\nusing namespace Eigen;\n\nint main(){\n using std::cout;\n using std::endl;\n\n MatrixXd A = MatrixXd::Zero(2,2);\n MatrixXd B = MatrixXd::Zero(2,2);\n\n A(0, 0) = 1;\n A(0, 1) = 2;\n A(1, 0) = 3;\n A(1, 1) = 4;\n\n B(0, 0) = 5;\n B(0, 1) = 6;\n B(1, 0) = 7;\n B(1, 1) = 8;\n\n cout << \"Same Dimension Matrix Multiply\" << endl;\n cout << A.rows() << \" \" << A.cols() << endl;\n cout << A*B << endl; // 行列の積\n cout << A.array() * B.array() << endl; // 要素積\n\n MatrixXd X = MatrixXd::Zero(2,3);\n MatrixXd Y = MatrixXd::Zero(3,2);\n\n X << 1,2,3, 4,5,6;\n Y << 1,2, 3,4, 5,6;\n\n cout << \"Different Dimension Matrix Multiply\" << endl;\n cout << \"X shape: \" << X.rows() << \" \" << X.cols() << endl;\n cout << \"Y shape: \" << Y.rows() << \" \" << Y.cols() << endl;\n cout << X * Y << endl;\n cout << X.array() * Y.transpose().array() << endl;\n\n return 0;\n}", "meta": {"hexsha": "50104e2d423b914a6e1ee901359ff34350ec0dc2", "size": 935, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/eigen_sample_operation.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "ch3/eigen_sample_operation.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch3/eigen_sample_operation.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": 22.8048780488, "max_line_length": 63, "alphanum_fraction": 0.4748663102, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7613639263479469}} {"text": "#pragma once\n#include \n#include \n#include \n\n#include \"stiffness_matrix.hpp\"\n\n//! Sparse Matrix type. Makes using this type easier.\ntypedef Eigen::SparseMatrix SparseMatrix;\n\n//! Used for filling the sparse matrix.\ntypedef Eigen::Triplet Triplet;\n\n//----------------AssembleMatrixBegin----------------\n//! Assemble the stiffness matrix\n//! for the linear system\n//!\n//! @param[out] A will at the end contain the Galerkin matrix\n//! @param[in] vertices a list of triangle vertices\n//! @param[in] dofs a list of the dofs' indices in each triangle\ntemplate \nvoid assembleStiffnessMatrix(Matrix &A, const Eigen::MatrixXd &vertices, const Eigen::MatrixXi &dofs, const int &N) {\n\tconst int numberOfElements = dofs.rows();\n\tA.resize(N, N);\n\n\tstd::vector triplets;\n\n\ttriplets.reserve(numberOfElements * 6 * 10);\n\t// (write your solution here)\n\tfor (int i = 0; i < numberOfElements; ++i) {\n\t\tauto &indexSet = dofs.row(i);\n\n\t\tconst auto &a = vertices.row(indexSet(0));\n\t\tconst auto &b = vertices.row(indexSet(1));\n\t\tconst auto &c = vertices.row(indexSet(2));\n\n\t\tEigen::MatrixXd stiffnessMatrix;\n\t\tcomputeStiffnessMatrix(stiffnessMatrix, a, b, c);\n\n\t\tfor (int n = 0; n < 6; ++n) {\n\t\t\tfor (int m = 0; m < 6; ++m) {\n\t\t\t\tauto triplet = Triplet(indexSet(n), indexSet(m), stiffnessMatrix(n, m));\n\t\t\t\ttriplets.push_back(triplet);\n\t\t\t}\n\t\t}\n\t}\n\tA.setFromTriplets(triplets.begin(), triplets.end());\n}\n//----------------AssembleMatrixEnd----------------\n", "meta": {"hexsha": "4108d492d40aae86aa19813c7909ff9d39174925", "size": 1505, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series3/2d-poissonqFEM/stiffness_matrix_assembly.hpp", "max_stars_repo_name": "westernmagic/NumPDE", "max_stars_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "series3/2d-poissonqFEM/stiffness_matrix_assembly.hpp", "max_issues_repo_name": "westernmagic/NumPDE", "max_issues_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-04-01T22:52:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T16:21:55.000Z", "max_forks_repo_path": "series3/2d-poissonqFEM/stiffness_matrix_assembly.hpp", "max_forks_repo_name": "westernmagic/NumPDE", "max_forks_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1, "max_line_length": 117, "alphanum_fraction": 0.6697674419, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7611264404531293}} {"text": "/**\n * @file kalman_filter.h\n * @brief Kalman Filter.\n * \n */\n\n#ifndef KALMAN_FILTER_H\n#define KALMAN_FILTER_H\n\n#include \n\nnamespace filter\n{\n\nclass KalmanFilter\n{\n public:\n /**\n * @brief Create a Kalman filter.\n * \n * @param C Output matrix\n * @param Q Process noise covariance\n * @param R Measurement noise covariance\n * @param P Estimate error covariance\n */\n KalmanFilter(\n const Eigen::MatrixXd& A,\n const Eigen::MatrixXd& C,\n const Eigen::MatrixXd& Q,\n const Eigen::MatrixXd& R,\n const Eigen::MatrixXd& P\n );\n ~KalmanFilter() {};\n\n /**\n * @brief Initialize the filter with initial states as zero.\n * \n */\n void init();\n\n /**\n * @brief Initialize the filter with an estimation on the initial states.\n * @param t0 initial timestamp.\n * @param x0 estimated state of the system.\n * \n */\n void init(double t0, const Eigen::VectorXd& x0);\n\n /**\n * @brief An adaptive Kalman filter.\n * @brief Update the estimated state based on measured values, using the given time step and dynamics matrix.\n * @param y measurements.\n * @param dt timestamp.\n * \n */\n Eigen::VectorXd compute(const Eigen::VectorXd& y, double dt);\n\n private:\n // Matrices for computation.\n Eigen::MatrixXd A, C, Q, R, P, K, P0;\n\n // Systems dimension.\n int m; // Number of measurements.\n int n; // Number of states.\n\n Eigen::MatrixXd I; // Identity matrix.\n Eigen::VectorXd x_hat, x_hat_new; // Estimated states.\n\n // Initial timer.\n double t0;\n\n // Flag.\n bool initialized;\n};\n\n} // namespace controller\n\n#endif /* KALMAN_FILTER_H */\n", "meta": {"hexsha": "6da8874ff4b11b62aa4584ea5bf65feaaa09ac8f", "size": 1889, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/signal_processing/include/kalman_filter.hpp", "max_stars_repo_name": "duckstarr/controller", "max_stars_repo_head_hexsha": "ed8020a4ba010981a6ea7377f39f0d1490359450", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-05-15T21:58:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T04:34:54.000Z", "max_issues_repo_path": "src/signal_processing/include/kalman_filter.hpp", "max_issues_repo_name": "duckstarr/controller", "max_issues_repo_head_hexsha": "ed8020a4ba010981a6ea7377f39f0d1490359450", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/signal_processing/include/kalman_filter.hpp", "max_forks_repo_name": "duckstarr/controller", "max_forks_repo_head_hexsha": "ed8020a4ba010981a6ea7377f39f0d1490359450", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9113924051, "max_line_length": 117, "alphanum_fraction": 0.5489677078, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939024825960626, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7610598161589076}} {"text": "/******************************************************************************\n * 反射衛星砲: 数学モデルユーティリティ関数\n *****************************************************************************/\n\n#ifndef __MATHEMATIC_UTILS_HPP__\n#define __MATHEMATIC_UTILS_HPP__\n\n#include \n#include \n#include \n\ntypedef std::vector > Vector3dSet;\n\n// 点P1,P2の間の距離の2乗を求める\ndouble distance2(const Eigen::Vector3d& P1, const Eigen::Vector3d& P2);\n\n// ベクトルX を正規化したベクトルを求める\nEigen::Vector3d normalize(const Eigen::Vector3d& X);\n\n// ベクトルX が ベクトルa を軸として p[rad]回転したときのベクトルを求める\nEigen::Vector3d rotate(const Eigen::Vector3d& X, const Eigen::Vector3d& a, const double p);\n\n// ベクトルX が 法線ベクトルn の面に入射したときの反射ベクトルを求める\nEigen::Vector3d reflect(const Eigen::Vector3d& X, const Eigen::Vector3d& n);\n\n// 点の集合P={p1,p2,...} のうち、点Oに最も近い点の集合(⊆P)を求める\nVector3dSet neighoring(const Eigen::Vector3d& O, const Vector3dSet& P);\n\n// 直線L(P,v) が楕円体E(O,R)の表面を通過,接触する座標を求める\n// ただし実数解のみ\nVector3dSet intersection(const Eigen::Vector3d& P, const Eigen::Vector3d& v,\n const Eigen::Vector3d& O, const Eigen::Vector3d& R);\n\n// 点P が楕円体E(O,R)の中にあるかどうか調べる\nbool inner_elipsoid(const Eigen::Vector3d& P, const Eigen::Vector3d& O, const Eigen::Vector3d& R);\n\n#endif // __MATHEMATIC_UTILS_HPP__\n\n", "meta": {"hexsha": "c39f6941d8b62a0bf66a0826339544ef0c7ce19a", "size": 1332, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mathematic_utils.hpp", "max_stars_repo_name": "earth2001y/satellite-reflector-beam-solver", "max_stars_repo_head_hexsha": "3dba42e67c48295fcdcbe631c5a1b8330e36b5a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mathematic_utils.hpp", "max_issues_repo_name": "earth2001y/satellite-reflector-beam-solver", "max_issues_repo_head_hexsha": "3dba42e67c48295fcdcbe631c5a1b8330e36b5a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mathematic_utils.hpp", "max_forks_repo_name": "earth2001y/satellite-reflector-beam-solver", "max_forks_repo_head_hexsha": "3dba42e67c48295fcdcbe631c5a1b8330e36b5a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-21T01:31:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-21T01:31:31.000Z", "avg_line_length": 34.1538461538, "max_line_length": 98, "alphanum_fraction": 0.6569069069, "num_tokens": 543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654159388319, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7609198461785471}} {"text": "/***************************************************************************\r\n/* Javier Juan Albarracin - jajuaal1@ibime.upv.es */\r\n/* Universidad Politecnica de Valencia, Spain */\r\n/* */\r\n/* Copyright (C) 2014 Javier Juan Albarracin */\r\n/* */\r\n/***************************************************************************\r\n* Non-Negative Matrix Factorization *\r\n***************************************************************************/\r\n\r\n#ifndef NNMF_HPP\r\n#define NNMF_HPP\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#define SQRTEPS 1.490116119384766e-08\r\n\r\n// [1] C. Boutsidis, E. Gallopoulos. SVD based initialization:A head start for nonnegative matrix factorization. Pattern Recognition 41 (2008) 1350–1362\r\n\r\nusing namespace Eigen;\r\n\r\nclass NNMF\r\n{\r\npublic:\r\n\tenum Algorithm { ALS, MUR };\r\n\r\n\tNNMF(const int maxIterations = 200, const double threshold = 1e-4, const double tolerance = 1e-4, const bool verbose = false);\r\n\t\r\n\ttemplate \r\n\tvoid compute(const MatrixBase &dataset, const int K, const Algorithm algorithm = ALS);\r\n\ttemplate \r\n\tvoid compute(const MatrixBase &dataset, const MatrixXd &W0, const MatrixXd &H0, const Algorithm algorithm = ALS);\r\n\t\r\n\tMatrixXd W() const { return m_W; }\r\n\tMatrixXd H() const { return m_H; }\r\n\t\r\nprivate:\r\n\ttemplate \r\n\tvoid nnmf(const MatrixXd &dataset);\r\n\t\r\n\ttemplate \r\n\tvoid SVDInitialization(const MatrixBase &dataset, const int K);\r\n\tvoid standard_form();\r\n\t\r\n\tMatrixXd m_W;\r\n\tMatrixXd m_H;\r\n\tint m_components;\r\n\tint m_maxIterations;\r\n\tdouble m_threshold;\r\n\tdouble m_tolerance;\r\n\tbool m_verbose;\r\n};\r\n\r\n/***************************** Implementation *****************************/\r\n\r\nNNMF::NNMF(const int maxIterations, const double threshold, const double tolerance, const bool verbose)\r\n: m_W(MatrixXd()), m_H(MatrixXd()), m_components(0), m_maxIterations(maxIterations), m_threshold(threshold), m_tolerance(tolerance), m_verbose(verbose)\r\n{\r\n}\r\n\r\ntemplate\r\nvoid NNMF::compute(const MatrixBase &dataset, const int K, const Algorithm algorithm)\r\n{\r\n\tif (K >= dataset.cols())\r\n\t{\r\n\t\tm_W = dataset.derived().cast();\r\n\t\tm_H = MatrixXd::Identity(K, K);\r\n\t\treturn;\r\n\t}\r\n\r\n\tif (K >= dataset.rows())\r\n\t{\r\n\t\tm_W = MatrixXd::Identity(K, K);\r\n\t\tm_H = dataset.derived().cast();\r\n\t\treturn;\r\n\t}\r\n\t\r\n\t// Set components\r\n\tm_components = K;\r\n\t\r\n\t// Singular Value Decomposition initialization\r\n\tSVDInitialization(dataset, K);\r\n\r\n\t// Run Non-Negative Matrix Factorization decomposition\r\n\tif (algorithm == ALS)\r\n\t\tnnmf(dataset.derived().cast());\r\n\telse if (algorithm == MUR)\r\n\t\tnnmf(dataset.derived().cast());\r\n\telse\r\n\t\tnnmf(dataset.derived().cast());\r\n}\r\n\r\ntemplate\r\nvoid NNMF::compute(const MatrixBase &dataset, const MatrixXd &W0, const MatrixXd &H0, const Algorithm algorithm)\r\n{\r\n\t// Set components\r\n\tm_components = W0.cols();\r\n\t\r\n\t// Initialize W and H matrices\r\n\tm_W = W0;\r\n\tm_H = H0;\r\n\r\n\t// Run Non-Negative Matrix Factorization decomposition\r\n\tif (algorithm == ALS)\r\n\t\tnnmf(dataset.derived().cast());\r\n\telse if (algorithm == MUR)\r\n\t\tnnmf(dataset.derived().cast());\r\n\telse\r\n\t\tnnmf(dataset.derived().cast());\r\n}\r\n\r\ntemplate \r\nvoid NNMF::nnmf(const MatrixXd &dataset)\r\n{\r\n\t// Set number of elements\r\n\tconst double NM = (double) dataset.size();\r\n\r\n\t// Declare previous iteration matrices and error\r\n\tMatrixXd W0 = m_W;\r\n\tMatrixXd H0 = m_H;\r\n\tdouble dnorm0 = 0;\r\n\t\r\n\tif (m_verbose)\r\n\t{\r\n\t\tmexPrintf(\"Iteration\\t\\tMax iterations\\t\\tRMSE\\t\\t\\tRatio\\t\\t\\tThreshold\\t\\tDelta\\t\\t\\tTolerance\\n\");\r\n\t\tmexPrintf(\"-------------------------------------------------------------------------------------------------------------\\n\");\r\n\t}\r\n\t\r\n\t// Constant matrices\r\n\tconst MatrixXd H_MUR_SQRTEPS = MatrixXd::Constant(m_components, dataset.cols(), SQRTEPS);\r\n\tconst MatrixXd W_MUR_SQRTEPS = MatrixXd::Constant(dataset.rows(), m_components, SQRTEPS);\r\n\t\r\n\tfor (int i = 0; i < m_maxIterations; ++i)\r\n\t{\r\n\t\tif (AlternatingLeastSquares)\r\n\t\t{\r\n\t\t\t// Update H\r\n\t\t\tm_H = W0.fullPivHouseholderQr().solve(dataset).cwiseMax(0);\r\n\t\t\t// Update W\r\n\t\t\tm_W = m_H.transpose().fullPivHouseholderQr().solve(dataset.transpose()).transpose().cwiseMax(0);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t// Update H\r\n\t\t\tMatrixXd numer = W0.transpose() * dataset;\r\n\t\t\tm_H = H0.cwiseProduct(numer.cwiseQuotient(((W0.transpose() * W0) * H0) + H_MUR_SQRTEPS)).cwiseMax(0);\r\n\t\t\t// Update W\r\n\t\t\tnumer = dataset * m_H.transpose();\r\n\t\t\tm_W = W0.cwiseProduct(numer.cwiseQuotient((W0 * (m_H * m_H)) + W_MUR_SQRTEPS)).cwiseMax(0);\r\n\t\t}\r\n\t\t\r\n\t\t// Compute squared error\r\n\t\tconst ArrayXXd d = dataset - (m_W * m_H);\r\n\t\tconst double dnorm = std::sqrt((d * d).sum() / NM);\t\t\r\n\t\tconst double dW = ((m_W - W0).cwiseAbs() / (SQRTEPS + W0.cwiseAbs().maxCoeff())).maxCoeff();\r\n\t\tconst double dH = ((m_H - H0).cwiseAbs() / (SQRTEPS + H0.cwiseAbs().maxCoeff())).maxCoeff();\r\n\t\tconst double delta = std::max(dW, dH);\r\n\t\t\r\n\t\tif (m_verbose)\r\n\t\t{\r\n\t\t\tmexPrintf(\"%d\\t\\t\\t\\t%d\\t\\t\\t\\t\\t%.2e\\t\\t%.2e\\t\\t%.2e\\t\\t%.2e\\t\\t%.2e\\n\", i+1, m_maxIterations, dnorm, (dnorm0 - dnorm), (m_threshold * std::max(1.0, dnorm0)), delta, m_tolerance);\r\n\t\t\tmexEvalString(\"drawnow\");\r\n\t\t}\r\n\t\t\r\n\t\tif (i > 0)\r\n\t\t{\r\n\t\t\tif (delta <= m_tolerance)\r\n\t\t\t{\r\n\t\t\t\tstandard_form();\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\tif (dnorm0 - dnorm <= (m_threshold * std::max(1.0, dnorm0)))\r\n\t\t\t{\r\n\t\t\t\tstandard_form();\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tdnorm0 = dnorm;\r\n\t\tW0 = m_W;\r\n\t\tH0 = m_H;\r\n\t}\r\n}\r\n\r\ntemplate \r\nvoid NNMF::SVDInitialization(const MatrixBase &dataset, const int K)\r\n{\r\n\t// Allocate memory\r\n\tm_W.resize(dataset.rows(), K);\r\n\tm_H.resize(K, dataset.cols());\r\n\t\r\n\t// Perform SVD decomposition\r\n\tJacobiSVD svd(dataset, ComputeThinU | ComputeThinV);\r\n\tMatrixXd U = svd.matrixU();\r\n\tMatrixXd V = svd.matrixV();\r\n\tVectorXd S = svd.singularValues();\r\n\t\r\n\t// Retain only the largest K eigen values and eigen vectors\r\n\tS = S.segment(0, K).eval();\r\n\tU = U.block(0, 0, U.rows(), K).eval();\r\n\tV = V.block(0, 0, V.rows(), K).eval();\r\n\t\r\n\t// Perform initialization as suggested in [1]\r\n\tm_W.col(0) = std::sqrt(S(0)) * U.col(0);\r\n\tm_H.row(0) = std::sqrt(S(0)) * V.col(0).transpose();\r\n\t\r\n\tfor (int i = 1; i < K; ++i)\r\n\t{\r\n\t\tconst VectorXd Uip = U.col(i).cwiseMax(0);\r\n\t\tconst VectorXd Uin = U.col(i).cwiseMin(0).cwiseAbs();\r\n\t\t\r\n\t\tconst VectorXd Vip = V.col(i).cwiseMax(0);\r\n\t\tconst VectorXd Vin = V.col(i).cwiseMin(0).cwiseAbs();\r\n\t\t\r\n\t\tconst double UipNorm = Uip.norm();\r\n\t\tconst double VipNorm = Vip.norm();\r\n\t\t\r\n\t\tconst double UinNorm = Uin.norm();\r\n\t\tconst double VinNorm = Vin.norm();\r\n\t\t\r\n\t\tconst double mp = UipNorm * VipNorm;\r\n\t\tconst double mn = UinNorm * VinNorm;\r\n\t\t\r\n\t\tVectorXd u;\r\n\t\tVectorXd v;\r\n\t\tdouble sigma;\r\n\t\tif (mp > mn)\r\n\t\t{\r\n\t\t\tu = Uip / UipNorm;\r\n\t\t\tv = Vip / VipNorm;\r\n\t\t\tsigma = mp;\t\t\t\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tu = Uin / UinNorm;\r\n\t\t\tv = Vin / VinNorm;\r\n\t\t\tsigma = mn;\t\t\t\r\n\t\t}\r\n\t\tm_W.col(i) = std::sqrt(S(i) * sigma) * u;\r\n\t\tm_H.row(i) = std::sqrt(S(i) * sigma) * v.transpose();\r\n\t}\r\n}\r\n\r\nvoid NNMF::standard_form()\r\n{\r\n\t// Put in standard form\r\n\tRowVectorXd Hlen = m_H.cwiseProduct(m_H).rowwise().sum().cwiseSqrt();\r\n\t\r\n\tfor (int i = 0; i < Hlen.size(); ++i)\r\n\t\tHlen(i) = Hlen(i) == 0 ? 1.0 : Hlen(i);\r\n\t\r\n\tfor (int i = 0; i < m_W.rows(); ++i)\r\n\t\tm_W.row(i) = m_W.row(i).cwiseProduct(Hlen);\r\n\t\r\n\tfor (int i = 0; i < m_H.cols(); ++i)\r\n\t\tm_H.col(i) = m_H.col(i).cwiseQuotient(Hlen.transpose());\r\n\t\r\n\tconst RowVectorXd magnitude = m_W.cwiseProduct(m_W).colwise().sum();\r\n\tstd::vector y(magnitude.size());\r\n int n = 0;\r\n std::generate(std::begin(y), std::end(y), [&] { return n++; });\r\n\tstd::sort(std::begin(y), std::end(y), [&](int i1, int i2) { return magnitude(i1) > magnitude(i2); });\r\n\t\r\n\tconst MatrixXd Wcopy = m_W;\r\n\tconst MatrixXd Hcopy = m_H;\r\n\tfor (int i = 0; i < magnitude.size(); ++i)\r\n\t{\r\n\t\tm_W.col(i) = Wcopy.col(y[i]);\r\n\t\tm_H.row(i) = Hcopy.row(y[i]);\r\n\t}\r\n}\r\n\r\n#endif", "meta": {"hexsha": "353aa2e69c7ca1791116fa65abfcbd5dcea7865b", "size": 8333, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NNMF.hpp", "max_stars_repo_name": "javierjuan/decomposition", "max_stars_repo_head_hexsha": "cc9c1ed51e915847f4e7b5e26d3e130e89d88473", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NNMF.hpp", "max_issues_repo_name": "javierjuan/decomposition", "max_issues_repo_head_hexsha": "cc9c1ed51e915847f4e7b5e26d3e130e89d88473", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NNMF.hpp", "max_forks_repo_name": "javierjuan/decomposition", "max_forks_repo_head_hexsha": "cc9c1ed51e915847f4e7b5e26d3e130e89d88473", "max_forks_repo_licenses": ["Apache-2.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.1920289855, "max_line_length": 184, "alphanum_fraction": 0.5874234969, "num_tokens": 2367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541528387691, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7609198430623179}} {"text": "/**\n * @file odesolve.cc\n * @brief NPDE homework ODESolve code\n * @author ?, Philippe Peter\n * @date 18.03.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"odesolve.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"../../../lecturecodes/helperfiles/polyfit.h\"\n\nnamespace ODESolve {\n\n/* SAM_LISTING_BEGIN_2 */\ndouble TestCvpExtrapolatedEuler() {\n double conv_rate;\n double T = 1.0;\n double y0 = 0.0;\n auto f = [](double y) -> double { return 1.0 + y * y; };\n\n auto Psi = [&f](double h, double y0) -> double { return y0 + h * f(y0); };\n unsigned p = 1;\n\n // lambda corresponding to \\tilde{\\psi}\n auto Psi_tilde = [&Psi, &f, &p](double h, double y0) -> double {\n return PsiTilde(Psi, p, h, y0);\n };\n\n // exact value\n double y_ex1 = std::tan(T);\n\n // values for convergence study\n Eigen::ArrayXd err(11);\n Eigen::ArrayXd M(11);\n\n std::cout << \"Error table for equidistant steps:\" << std::endl;\n std::cout << \"M\"\n << \"\\t\"\n << \"Error\" << std::endl;\n\n for (int i = 0; i < 11; ++i) {\n M(i) = std::pow(2, i + 2);\n double yT = OdeIntEqui(Psi_tilde, T, y0, M(i)).back();\n err(i) = std::abs(yT - y_ex1);\n std::cout << M(i) << \"\\t\" << err(i) << std::endl;\n }\n // compute fitted rate\n Eigen::VectorXd coeffs = polyfit(M.log(), err.log(), 1);\n conv_rate = -coeffs(0);\n return conv_rate;\n}\n\n/* SAM_LISTING_BEGIN_4 */\nstd::pair, std::vector> SolveTangentIVP() {\n auto f = [](double y) -> double { return 1.0 + y * y; };\n double y0 = 0.0;\n\n double T = 1.5;\n unsigned p = 1;\n double h0 = 1. / 100.;\n\n auto Psi = [&f](double h, double y0) -> double { return y0 + h * f(y0); };\n // run adaptive algoritm\n return OdeIntSsCtrl(Psi, p, y0, T, h0, 10e-4, 10e-6, 10e-5);\n\n}\n/* SAM_LISTING_END_4 */\n\n} // namespace ODESolve\n", "meta": {"hexsha": "2448f066d370107ae1bd1de27a4ef1c7a3a9922a", "size": 1844, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ODESolve/mastersolution/odesolve.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/ODESolve/mastersolution/odesolve.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/ODESolve/mastersolution/odesolve.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 24.2631578947, "max_line_length": 76, "alphanum_fraction": 0.5883947939, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695836, "lm_q2_score": 0.8670357718273068, "lm_q1q2_score": 0.7608037553606927}} {"text": "#include \n#include \n#include \n\nusing namespace std;\nusing namespace Eigen;\n\n#define PRINT_MAT(X) cout << #X << \":\\n\" << X << endl\n\nvoid Example1(void)\n{ /*\n This Function I almost copied from following link.\n https://gist.github.com/AtsushiSakai/5175898#file-geometrysample-cpp-L23\n And here is the copy right of this function.\n FileName: GeometrySample.cpp Line 23 to Line 37 \n Discription: EigenのGeometry関連の関数のサンプル \n Author: Atsushi Sakai\n Update: 2013/03/16\n */\n\n cout<<\"====1. 2次元空間における回転行列を使用した点の回転=====\"< m;// = MatrixXd::Ones(4,4);\n\n m <<\n 1,2,3,4,\n 5,6,7,8,\n 9,10,11,12,\n 13,14,15,16;\n \n cout << m << endl;\n\n Vector2d v1 = m.block(0,3,2,1);\n Vector2d v2 = m.block(2,0,2,1);\n\n cout << typeid(v1).name() << endl;\n \n cout << v1.transpose() << endl;\n cout << v2.transpose() << endl;\n cout << (v1 + v2).transpose() << endl;\n cout << v1.lpNorm<2>() << endl;\n\n cout << ((v1+v2)/2.).transpose() << endl;\n cout << ((v1+v2)/2.).lpNorm<1>() << endl;\n}\n\nclass cltst{\npublic:\n void b(const double& a)\n { b_ = a; };\n\n void c(const vector& c)\n { c_ = c; };\n \n double b(void) const\n { return b_; };\n\n vector c(void) const\n { return c_; };\n\n vector& c(void)\n { return c_; };\n \nprivate:\n double b_;\n vector c_;\n};\n\nvoid test(void)\n{\n cltst t;\n double a = 3;\n vector b{4,5,6};\n\n t.b(a);\n t.c(b);\n cout << t.b() << endl;\n for(size_t i=0; i& u = t.c();\n for(size_t i=0; i& a)\n{\n for(auto i=a.begin(); i!=a.end(); i++)\n cout << *i << \", \";\n cout << endl;\n}\n\nvoid test2(void)\n{\n func(vector{2,3,4});\n}\n\nint main(int argv, char** argc)\n{\n \n // Example1();\n // Example2();\n // Example3();\n Example4();\n // test();\n test2();\n \n return 0;\n}\n", "meta": {"hexsha": "c627fc44e57b37013e9fb5be9fb4ea2f2edb972f", "size": 3372, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/2d_transform.cpp", "max_stars_repo_name": "RyodoTanaka/eigen_example", "max_stars_repo_head_hexsha": "55da46919e02d0eb7cbea9da97ffa0f9067a6d98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/2d_transform.cpp", "max_issues_repo_name": "RyodoTanaka/eigen_example", "max_issues_repo_head_hexsha": "55da46919e02d0eb7cbea9da97ffa0f9067a6d98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/2d_transform.cpp", "max_forks_repo_name": "RyodoTanaka/eigen_example", "max_forks_repo_head_hexsha": "55da46919e02d0eb7cbea9da97ffa0f9067a6d98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-30T03:32:04.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-30T03:32:04.000Z", "avg_line_length": 19.0508474576, "max_line_length": 74, "alphanum_fraction": 0.5679122183, "num_tokens": 1273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389113, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7606452304079189}} {"text": "#ifndef HELP_FUNCTIONS_HPP\n#define HELP_FUNCTIONS_HPP\n#include \n#include \n#include \ntypedef Eigen::SparseMatrix SpMat; // declares a column-major sparse matrix type of double\ntypedef Eigen::Triplet T;\n\nvoid insertCoefficient(int id, int i, int j, double w, std::vector &coeffs,\n Eigen::VectorXd &b, const Eigen::VectorXd &boundary)\n{\n int n = int(boundary.size());\n int id1 = i + j * n;\n if (i == -1 || i == n)\n b(id) -= w * boundary(j); // constrained coefficient\n else if (j == -1 || j == n)\n b(id) -= w * boundary(i); // constrained coefficient\n else\n coeffs.push_back(T(id, id1, w)); // unknown coefficient\n}\nvoid buildProblem(std::vector &coefficients, Eigen::VectorXd &b, int n)\n{\n b.setZero();\n Eigen::ArrayXd boundary = Eigen::ArrayXd::LinSpaced(n, 0, M_PI).sin().pow(2);\n for (int j = 0; j < n; ++j)\n {\n for (int i = 0; i < n; ++i)\n {\n int id = i + j * n;\n insertCoefficient(id, i - 1, j, -1, coefficients, b, boundary);\n insertCoefficient(id, i + 1, j, -1, coefficients, b, boundary);\n insertCoefficient(id, i, j - 1, -1, coefficients, b, boundary);\n insertCoefficient(id, i, j + 1, -1, coefficients, b, boundary);\n insertCoefficient(id, i, j, 4, coefficients, b, boundary);\n }\n }\n}\nvoid saveAsBitmap(const Eigen::VectorXd &x, int n, const char *filename)\n{\n Eigen::Array bits = (x * 255).cast();\n QImage img(bits.data(), n, n, QImage::Format_Indexed8);\n img.setColorCount(256);\n for (int i = 0; i < 256; i++)\n img.setColor(i, qRgb(i, i, i));\n img.save(filename);\n}\n\n#endif", "meta": {"hexsha": "8f0473be0e8db112d0938793f3510e8e6bb13ce8", "size": 1967, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ICP/EigenChineseDocument-master/Eigen/Chapter3_SparseLinearAlgebra/HelpFunctions.hpp", "max_stars_repo_name": "Yihua-Ni/Tools", "max_stars_repo_head_hexsha": "b40c24b0b2a7025f13182fc5ed5bfcf63b389585", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ICP/EigenChineseDocument-master/Eigen/Chapter3_SparseLinearAlgebra/HelpFunctions.hpp", "max_issues_repo_name": "Yihua-Ni/Tools", "max_issues_repo_head_hexsha": "b40c24b0b2a7025f13182fc5ed5bfcf63b389585", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICP/EigenChineseDocument-master/Eigen/Chapter3_SparseLinearAlgebra/HelpFunctions.hpp", "max_forks_repo_name": "Yihua-Ni/Tools", "max_forks_repo_head_hexsha": "b40c24b0b2a7025f13182fc5ed5bfcf63b389585", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9791666667, "max_line_length": 107, "alphanum_fraction": 0.5368581596, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7606049384707071}} {"text": "// Kernel PCA using the Eigen library, by Tim Nugent 2014\n\n#include \n#include \n#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\nclass PCA{\n\npublic:\n\tPCA() : components(2), kernel_type(1), normalise(0), gamma(0.001), constant(1.0), order(2.0) {}\n\texplicit PCA(MatrixXd& d) : components(2), kernel_type(1), normalise(0), gamma(0.001), constant(1.0), order(2.0) {X = d;}\n\tvoid load_data(const char* data, char sep = ',');\n\tvoid set_components(const int i){components = i;};\n\tvoid set_kernel(const int i){kernel_type = i;};\t\n\tvoid set_normalise(const int i){normalise = i;};\n\tvoid set_gamma(const double i){gamma = i;};\n\tvoid set_constant(const double i){constant = i;};\n\tvoid set_order(const double i){order = i;};\n\tMatrixXd& get_transformed(){return transformed;}\t\n\tvoid run_pca();\n\tvoid run_kpca();\n\tvoid print();\n\tvoid write_transformed(string);\n\tvoid write_eigenvectors(string);\nprivate:\n\tdouble kernel(const VectorXd& a, const VectorXd& b);\n\tMatrixXd X, Xcentered, C, K, eigenvectors, transformed;\n\tVectorXd eigenvalues, cumulative;\n\tunsigned int components, kernel_type, normalise;\n\tdouble gamma, constant, order;\n\n};\n\nvoid PCA::load_data(const char* data, char sep){\n\n\t// Read data\n\tunsigned int row = 0;\n\tifstream file(data);\n\tif(file.is_open()){\n\t\tstring line,token;\n\t\twhile(getline(file, line)){\n\t\t\tstringstream tmp(line);\n\t\t\tunsigned int col = 0;\n\t\t\twhile(getline(tmp, token, sep)){\n\t\t\t\tif(X.rows() < row+1){\n\t\t\t\t\tX.conservativeResize(row+1,X.cols());\n\t\t\t\t}\n\t\t\t\tif(X.cols() < col+1){\n\t\t\t\t\tX.conservativeResize(X.rows(),col+1);\n\t\t\t\t}\n\t\t\t\tX(row,col) = atof(token.c_str());\n\t\t\t\tcol++;\n\t\t\t}\n\t\t\trow++;\n\t\t}\n\t\tfile.close();\n\t\tXcentered.resize(X.rows(),X.cols());\n\t}else{\n\t\tcout << \"Failed to read file \" << data << endl;\n\t}\n\n}\n\ndouble PCA::kernel(const VectorXd& a, const VectorXd& b){\n\n\t/*\n\t\tKernels\n\t\t1 = RBF\n\t\t2 = Polynomial\n\t\tTODO - add some of these these:\n\t\thttp://crsouza.blogspot.co.uk/2010/03/kernel-functions-for-machine-learning.html\t\n\n\t*/\n\tswitch(kernel_type){\n\t case 2 :\n\t \treturn(pow(a.dot(b)+constant,order));\n\t default : \n\t \treturn(exp(-gamma*((a-b).squaredNorm())));\n\t}\n\n}\n\nvoid PCA::run_kpca(){\n\n\t// Fill kernel matrix\n\tK.resize(X.rows(),X.rows());\n\tfor(unsigned int i = 0; i < X.rows(); i++){\n\t\tfor(unsigned int j = i; j < X.rows(); j++){\n\t\t\tK(i,j) = K(j,i) = kernel(X.row(i),X.row(j));\n\t\t\t//printf(\"k(%i,%i) = %f\\n\",i,j,K(i,j));\n\t\t}\t\n\t}\t\n\t//cout << endl << K << endl;\n\n\tEigenSolver edecomp(K);\n\teigenvalues = edecomp.eigenvalues().real();\n\teigenvectors = edecomp.eigenvectors().real();\n\tcumulative.resize(eigenvalues.rows());\n\tvector > eigen_pairs; \n\tdouble c = 0.0; \n\tfor(unsigned int i = 0; i < eigenvectors.cols(); i++){\n\t\tif(normalise){\n\t\t\tdouble norm = eigenvectors.col(i).norm();\n\t\t\teigenvectors.col(i) /= norm;\n\t\t}\n\t\teigen_pairs.push_back(make_pair(eigenvalues(i),eigenvectors.col(i)));\n\t}\n\t// http://stackoverflow.com/questions/5122804/sorting-with-lambda\n\tsort(eigen_pairs.begin(),eigen_pairs.end(), [](const pair a, const pair b) -> bool {return (a.first > b.first);} );\n\tfor(unsigned int i = 0; i < eigen_pairs.size(); i++){\n\t\teigenvalues(i) = eigen_pairs[i].first;\n\t\tc += eigenvalues(i);\n\t\tcumulative(i) = c;\n\t\teigenvectors.col(i) = eigen_pairs[i].second;\n\t}\n\ttransformed.resize(X.rows(),components);\n\n\tfor(unsigned int i = 0; i < X.rows(); i++){\n\t\tfor(unsigned int j = 0; j < components; j++){\n\t\t\tfor (int k = 0; k < K.rows(); k++){\n transformed(i,j) += K(i,k) * eigenvectors(k,j);\n\t\t \t}\n\t\t}\n\t}\t\n\n\t/*\n\tcout << \"Input data:\" << endl << X << endl << endl;\n\tcout << \"Centered data:\"<< endl << Xcentered << endl << endl;\n\tcout << \"Centered kernel matrix:\" << endl << Kcentered << endl << endl;\n\tcout << \"Eigenvalues:\" << endl << eigenvalues << endl << endl;\t\n\tcout << \"Eigenvectors:\" << endl << eigenvectors << endl << endl;\t\n\t*/\n\tcout << \"Sorted eigenvalues:\" << endl;\n\tfor(unsigned int i = 0; i < eigenvalues.rows(); i++){\n\t\tif(eigenvalues(i) > 0){\n\t\t\tcout << \"PC \" << i+1 << \": Eigenvalue: \" << eigenvalues(i);\n\t\t\tprintf(\"\\t(%3.3f of variance, cumulative = %3.3f)\\n\",eigenvalues(i)/eigenvalues.sum(),cumulative(i)/eigenvalues.sum());\n\t\t}\n\t}\n\tcout << endl;\n\t//cout << \"Sorted eigenvectors:\" << endl << eigenvectors << endl << endl;\t\n\t//cout << \"Transformed data:\" << endl << transformed << endl << endl;\t\n}\n\nvoid PCA::run_pca(){\n\n\t// http://stackoverflow.com/questions/15138634/eigen-is-there-an-inbuilt-way-to-calculate-sample-covariance\n\tXcentered = X.rowwise() - X.colwise().mean();\t\n\tC = (Xcentered.adjoint() * Xcentered) / double(X.rows());\n\tEigenSolver edecomp(C);\n\teigenvalues = edecomp.eigenvalues().real();\n\teigenvectors = edecomp.eigenvectors().real();\n\tcumulative.resize(eigenvalues.rows());\n\tvector > eigen_pairs; \n\tdouble c = 0.0; \n\tfor(unsigned int i = 0; i < eigenvectors.cols(); i++){\n\t\tif(normalise){\n\t\t\tdouble norm = eigenvectors.col(i).norm();\n\t\t\teigenvectors.col(i) /= norm;\n\t\t}\n\t\teigen_pairs.push_back(make_pair(eigenvalues(i),eigenvectors.col(i)));\n\t}\n\t// http://stackoverflow.com/questions/5122804/sorting-with-lambda\n\tsort(eigen_pairs.begin(),eigen_pairs.end(), [](const pair a, const pair b) -> bool {return (a.first > b.first);} );\n\tfor(unsigned int i = 0; i < eigen_pairs.size(); i++){\n\t\teigenvalues(i) = eigen_pairs[i].first;\n\t\tc += eigenvalues(i);\n\t\tcumulative(i) = c;\n\t\teigenvectors.col(i) = eigen_pairs[i].second;\n\t}\n\ttransformed = Xcentered * eigenvectors;\n\n}\n\nvoid PCA::print(){\n\n\tcout << \"Input data:\" << endl << X << endl << endl;\n\tcout << \"Centered data:\"<< endl << Xcentered << endl << endl;\n\tcout << \"Covariance matrix:\" << endl << C << endl << endl;\n\tcout << \"Eigenvalues:\" << endl << eigenvalues << endl << endl;\t\n\tcout << \"Eigenvectors:\" << endl << eigenvectors << endl << endl;\t\n\tcout << \"Sorted eigenvalues:\" << endl;\n\tfor(unsigned int i = 0; i < eigenvalues.rows(); i++){\n\t\tif(eigenvalues(i) > 0){\n\t\t\tcout << \"PC \" << i+1 << \": Eigenvalue: \" << eigenvalues(i);\n\t\t\tprintf(\"\\t(%3.3f of variance, cumulative = %3.3f)\\n\",eigenvalues(i)/eigenvalues.sum(),cumulative(i)/eigenvalues.sum());\n\t\t}\n\t}\n\tcout << endl;\n\tcout << \"Sorted eigenvectors:\" << endl << eigenvectors << endl << endl;\t\n\tcout << \"Transformed data:\" << endl << X * eigenvectors << endl << endl;\t\n\t//cout << \"Transformed centred data:\" << endl << transformed << endl << endl;\t\n\n}\n\nvoid PCA::write_transformed(string file){\n\n\tofstream outfile(file);\n\tfor(unsigned int i = 0; i < transformed.rows(); i++){\n\t\tfor(unsigned int j = 0; j < transformed.cols(); j++){\n\t\t\toutfile << transformed(i,j);\n\t\t\tif(j != transformed.cols()-1) outfile << \",\";\n\t\t}\t\n\t\toutfile << endl;\n\t}\n\toutfile.close();\n\tcout << \"Written file \" << file << endl;\n\n}\t\n\nvoid PCA::write_eigenvectors(string file){\n\n\tofstream outfile(file);\n\tfor(unsigned int i = 0; i < eigenvectors.rows(); i++){\n\t\tfor(unsigned int j = 0; j < eigenvectors.cols(); j++){\n\t\t\toutfile << eigenvectors(i,j);\n\t\t\tif(j != eigenvectors.cols()-1) outfile << \",\";\n\t\t}\t\n\t\toutfile << endl;\n\t}\n\toutfile.close();\n\tcout << \"Written file \" << file << endl;\n\n}\t\n\nint main(int argc, const char* argv[]){\n\n\t/*\n\tif(argc < 2){\n\t\tcout << \"Usage:\\n\" << argv[0] << \" \" << endl;\n\t\tcout << \"File format:\\nX1,X2, ... Xn\\n\";\n\t\treturn(0);\n\t}\n\t*/\n\n\tPCA* P = new PCA();\n\tP->load_data(\"data/test.data\");\n\tP->run_pca();\n\tcout << \"Regular PCA (data/test.data):\" << endl;\n\tP->run_pca();\n\tP->print();\n\tdelete P;\n\n\tP = new PCA();\n\tP->load_data(\"data/wikipedia.data\");\n\tcout << \"Kernel PCA (data/wikipedia.data) - RBF kernel, gamma = 0.001:\" << endl;\n\tP->run_kpca();\n\tP->write_eigenvectors(\"data/eigenvectors_RBF_data.csv\");\n\tP->write_transformed(\"data/transformed_RBF_data.csv\");\n\tcout << endl;\t\n\tdelete P;\n\n\tP = new PCA();\n\tP->load_data(\"data/wikipedia.data\");\n\tP->set_kernel(2);\n\tP->set_constant(1);\n\tP->set_order(2);\n\tcout << \"Kernel PCA (data/wikipedia.data) - Polynomial kernel, order = 2, constant = 1:\" << endl;\n\tP->run_kpca();\n\tP->write_eigenvectors(\"data/eigenvectors_Polynomial_data.csv\");\n\tP->write_transformed(\"data/transformed_Polynomial_data.csv\");\t\n\tcout << endl;\t\n\tdelete P;\n\n\treturn(0);\n\n}\n\n", "meta": {"hexsha": "90f0d6435251b9ca20094386fc29616094aed88e", "size": 8185, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/kpca.cpp", "max_stars_repo_name": "qqgeogor/kpca-eigen", "max_stars_repo_head_hexsha": "9c30b7615e91556ea164d1e3c1c5c1a77e0b41c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-09-06T01:24:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:03:21.000Z", "max_issues_repo_path": "src/kpca.cpp", "max_issues_repo_name": "Pandinosaurus/kpca-eigen", "max_issues_repo_head_hexsha": "9c30b7615e91556ea164d1e3c1c5c1a77e0b41c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-11-12T01:46:09.000Z", "max_issues_repo_issues_event_max_datetime": "2015-11-12T14:24:38.000Z", "max_forks_repo_path": "src/kpca.cpp", "max_forks_repo_name": "Pandinosaurus/kpca-eigen", "max_forks_repo_head_hexsha": "9c30b7615e91556ea164d1e3c1c5c1a77e0b41c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-03-04T13:42:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T14:09:36.000Z", "avg_line_length": 29.9816849817, "max_line_length": 150, "alphanum_fraction": 0.6339645693, "num_tokens": 2421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938414, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.760416220057821}} {"text": "#include \n#include \n#include \n#include \n#include \n\nclass NatCSI{\npublic:\n\tNatCSI(const std::vector & t, const std::vector & y): \n\tt_(t),\n\ty_(y), \n\th(t.size()-1),\n\tc(t.size()) {\n\t\tassert ((t_.size() == y_.size()) && \"size missmatch (t & y)\");\n\t\tm=t.size();//n+1\n\t\tfor (int i = 0; i<(m-1); i++){\n\t\t\th(i)=t_[i+1]-t_[i];\n\t\t\tassert( ( h(i) > 0 ) && \"Error: array t must be sorted!\");\n\t\t}\n\t\t\n\t\tEigen::SparseMatrix A(m,m);\n Eigen::VectorXd b(m);\n\n A.reserve(3);\n\t\t\n\t\tA.coeffRef(0,0)=2/h(0);\n\t\tA.coeffRef(0,1)=1/h(0);\n\t\tA.coeffRef(m-1,m-1)=2/h(m-2);\n\t\tA.coeffRef(m-1,m-2)=1/h(m-2);\n\t\tdouble bold =(y[1]-y[0])/(h(0)*h(0));\n\t\tb(0)= 3*bold;\n\t\t\n\t\tfor (int i=1;i > lu;\n\t\tlu.compute(A);\n\t\tc = lu.solve(b);\n\t\t\n\t\t\n\t}\n\t\n\tdouble operator () (double x) const {\n\t\tassert( (x>=t_[0] && x<=t_[m-1]) && \"Error: x is not in [t(0),t(n)]\");\n\t\t\n\t\tauto j = ((std::lower_bound(t_.begin(), t_.end(), x)-t_.begin())-1);\n\t\tif (j==-1) j++;\n\t\t\n\t\tdouble tau = x - t_[j]/h(j);\n\t\tdouble tau2 = tau*tau;\n\t\tdouble tau3 = tau2*tau;\n\t\treturn y_[j] * (1.-3.*tau2 + 2* tau3) +\n\t\t\t\ty_[j+1] *(3*tau2-2*tau3) + \n\t\t\t\th(j)*c(j) *(tau-2*tau2+tau3) +\n\t\t\t\th(j)*c(j+1)*(-tau2+tau3);\t\n\t};\n\t\nprivate:\n\tstd::vector t_, y_;\n\tEigen::VectorXd h, c;\n\tsize_t m; //m=n+1\n\t\n};\n\n\nint main() {\n \n int n = 8, m = 100;\n std::vector t;\n std::vector y;\n t.resize(n);\n y.resize(n);\n for(int i = 0; i < n; ++i) {\n t[i] = (double) i / (n-1);\n y[i] = cos(t[i]);\n }\n \n NatCSI N(t,y);\n \n Eigen::VectorXd x = Eigen::VectorXd::LinSpaced(m, 0, 1);\n for(int i = 0; i < x.size(); ++i) {\n x(i) = N(x(i));\n }\n std::cout << x << std::endl;\n}\n\n\n", "meta": {"hexsha": "2143b1d0f85151747dd6d5cc7eae8a332b0ad7f2", "size": 2115, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS8/NatCSI.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS8/NatCSI.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS8/NatCSI.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.15, "max_line_length": 72, "alphanum_fraction": 0.5002364066, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7603297166401642}} {"text": "#include \n#include \n\n#include \n\n#include \n#include \n\n#define PI M_PI\n#define PI_HALF M_PI_2\n\nusing vector = Eigen::VectorXd;\n\n//! \\brief Golub-Welsh implementation 5.3.35\n//! \\param[in] n number of Gauss nodes\n//! \\param[out] w weights\n//! \\param[out] x nodes for interval [-1,1]\nvoid golubwelsh(int n, vector & w, vector & x) {\n w.resize(n);\n x.resize(n);\n if( n == 0 ) {\n x(0) = 0;\n w(0) = 2;\n } else {\n vector b(n-1);\n Eigen::MatrixXd J = Eigen::MatrixXd::Zero(n,n);\n\n for(int i = 1; i < n; ++i) {\n double d = (i) / sqrt(4. * i * i - 1.);\n J(i,i-1) = d;\n J(i-1,i) = d;\n }\n\n Eigen::EigenSolver eig(J);\n\n x = eig.eigenvalues().real();\n w = 2 * eig.eigenvectors().real().topRows<1>().cwiseProduct(eig.eigenvectors().real().topRows<1>());\n }\n}\n\n//! \\brief Compute \\int_a^b f(x) dx \\approx \\sum w_i f(x_i) (with scaling of w and x)\n//! \\tparam func template type for function handle f (e.g. lambda func.)\n//! \\param[in] f integrand\n//! \\param[in] w weights\n//! \\param[in] x nodes for interval [-1,1]\n//! \\param[in] a left boundary in [a,b]\n//! \\param[in] b right boundary in [a,b]\n//! \\return Approximation of integral \\int_a^b f(x) dx\ntemplate \ndouble quad(func&& f, const vector & w, const vector & x, double a, double b) {\n double I = 0;\n for(int i = 0; i < w.size(); ++i) {\n I += f( (x(i) + 1) * (b - a) / 2 + a ) * w(i);\n }\n return I * (b - a) / 2.;\n}\n\n//! \\brief Compute \\int_{-infty}^\\infty f(x) dx using transformation x = cot(t)\n//! \\tparam func template type for function handle f (e.g. lambda func.)\n//! \\param[in] n number of Gauss points\n//! \\param[in] f integrand\n//! \\return Approximation of integral \\int_{-infty}^\\infty f(x) dx\ntemplate \ndouble quadinf(int n, func&& f) {\n vector w, x;\n golubwelsh(n, w, x);\n // NOTE: no function cot available in c++, need to resort to trigonometric identities\n //! Both below are valid, the first computes two trigonometric functions\n auto ftilde = [&f] (double x) { return f(cos(x)/sin(x)) / pow(sin(x),2); };\n// auto ftilde = [&f] (double x) { double cot = tan(PI_HALF - x); return f(cot) * (1. + pow(cot,2)); };\n return quad(ftilde, w, x, 0, PI);\n}\n\nint main() {\n // Number of max Gauss pts.\n double N = 100;\n\n // Integrand and exact integral\n auto f = [] (double t) { return exp(-pow((t-1),2)); };\n double I_ex = sqrt(PI);\n \n // NOTE: We observe exponential convergence\n int sep = 12;\n std::cout << std::setw(sep) << \"Nodes\" << std::setw(sep) << \"Quadrature\" << std::setw(sep) << \"Exact\" << std::setw(sep) << \"Error\" << std::endl;\n for(int n = 1; n < N; ++n) {\n vector w, x;\n double QS = quadinf(n, f);\n// std::cout << std::setw(sep) << n << std::setw(sep) << QS << std::setw(sep) << I_ex << std::setw(sep) << std::abs(QS - I_ex) << std::endl;\n std::cout << std::setw(sep) << \" \" << std::abs(QS - I_ex) << std::endl;\n }\n}\n", "meta": {"hexsha": "0af39b16aab610ddf16df87535fc30847e521d06", "size": 3092, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/solutions/solutions_ps10/quadinf.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/solutions/solutions_ps10/quadinf.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/solutions/solutions_ps10/quadinf.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6086956522, "max_line_length": 148, "alphanum_fraction": 0.5620957309, "num_tokens": 1005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.760279319285815}} {"text": "#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace Eigen;\n\n\nint main(int argc, char **argv)\n{\n double ar = 1.0, br = 2.0, cr = 1.0;\n double ae = 2.0, be = -1.0, ce = 5.0;\n int N = 100;\n double w_sigma = 1.0;\n double inv_sigma = 1.0 / w_sigma;\n cv::RNG rng; // Opencv随机数产生器\n\n\n // 生成数据\n vector x_data, y_data;\n for (int i=0; i 0 && cost >= lastCost)\n {\n cout << \"cost >= lastCost, break!\" << endl;\n break;\n }\n\n ae += dx[0];\n be += dx[1];\n ce += dx[2];\n\n cout << \"iter = \" << iter << \", total cost = \" << cost << \", \\t\\t update = \" << dx.transpose() \n << \", \\t\\t estimated paras = \" << ae << \", \" << be << \", \" << ce << endl; \n\n \n if (fabs(cost - lastCost) < 1e-8)\n {\n break;\n }\n\n lastCost = cost;\n iter += 1; \n }\n chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n chrono::duration time_used = chrono::duration_cast> (t2-t1);\n\n cout << endl << \"Estimated paras a, b, c = \" << ae << \", \" << be << \", \" << ce << endl; \n cout << endl << \"Solve time cost = \" << time_used.count() << \"s\" << endl;\n\n\n\n return 0;\n}", "meta": {"hexsha": "b1367bbcd59e1d75a6476863adac365e15859b0a", "size": 2526, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "my_implementation_1/ch6/gaussNewton/gaussNewton.cpp", "max_stars_repo_name": "Mingrui-Yu/slambook2", "max_stars_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-09T14:18:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-09T14:18:15.000Z", "max_issues_repo_path": "my_implementation_1/ch6/gaussNewton/gaussNewton.cpp", "max_issues_repo_name": "Mingrui-Yu/slambook2", "max_issues_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "my_implementation_1/ch6/gaussNewton/gaussNewton.cpp", "max_forks_repo_name": "Mingrui-Yu/slambook2", "max_forks_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5242718447, "max_line_length": 103, "alphanum_fraction": 0.4568487728, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7602123194025456}} {"text": "// https://projecteuler.net/problem=56\n/*\nPowerful digit sum\n\nA googol (10^100) is a massive number:\none followed by one-hundred zeros;\n\n100^100 is almost unimaginably large:\none followed by two-hundred zeros.\n\nDespite their size, the sum of the digits in each number is only 1.\n\nConsidering natural numbers of the form, a^b, where a, b < 100,\nwhat is the maximum digital sum?\n\nSolution:\n\n*/\n\n#include \n#include \n#include \n#include \n#include \n\nauto digitCount(uint32_t a, uint32_t b) {\n\tusing namespace boost;\n\tmultiprecision::cpp_int p = a;\n\tp = multiprecision::pow(p, b);\n\tauto ans = p.str();\n\tuint32_t sum = 0;\n\tfor (const auto &c : ans)\n\t\tsum += c - '0';\n\treturn sum;\n}\n\nauto compute() {\n\tconstexpr uint32_t limit = 100;\n\n\tuint32_t max = 0;\n\tfor (uint32_t a = 1; a < limit; ++a)\n\t\tfor (uint32_t b = 1, c; b < limit; ++b)\n\t\t\tif (max < (c = digitCount(a, b)))\n\t\t\t\tmax = c;\n\n\treturn max;\n}\n\n#ifdef _MSC_VER\n\ttemplate \n\tinline void DoNotOptimize(const T &value) {\n\t\t__asm { lea ebx, value }\n\t}\n#else\n\ttemplate \n\t__attribute__((always_inline)) inline void DoNotOptimize(const T &value) {\n\t\tasm volatile(\"\" : \"+m\"(const_cast(value)));\n\t}\n#endif\n\nint main() {\n\tusing namespace std;\n\tusing namespace chrono;\n\tauto start = high_resolution_clock::now();\n\tauto result = compute();\n\tDoNotOptimize(result);\n\tcout << \"Done in \"\n\t\t<< duration_cast(high_resolution_clock::now() - start).count() / 1e6\n\t\t<< \" miliseconds.\" << endl;\n\tcout << result << endl;\n}\n", "meta": {"hexsha": "63c03b890d4e115189f7c03c4f79b88b5165fe63", "size": 1551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ProjectEuler/Problems/problem051_075/Solution056.cpp", "max_stars_repo_name": "ankitdixit/code-gems", "max_stars_repo_head_hexsha": "bdb30ba5c714f416dbf54d479d055458bde36085", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProjectEuler/Problems/problem051_075/Solution056.cpp", "max_issues_repo_name": "ankitdixit/code-gems", "max_issues_repo_head_hexsha": "bdb30ba5c714f416dbf54d479d055458bde36085", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProjectEuler/Problems/problem051_075/Solution056.cpp", "max_forks_repo_name": "ankitdixit/code-gems", "max_forks_repo_head_hexsha": "bdb30ba5c714f416dbf54d479d055458bde36085", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-09-30T06:26:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-20T14:41:55.000Z", "avg_line_length": 21.5416666667, "max_line_length": 83, "alphanum_fraction": 0.6776273372, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122213606241, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.759982836943504}} {"text": "\n#include \n\n#include \n#include \"src/rk_implementer.hpp\"\n#include \"src/rk_solvers.hpp\"\n\n\nint main() {\n\n /**\n * Setting global variables, the time we are integrating over\n * and the number of integration steps we take in this time.\n * \n * We also define the function f representing our ODE\n * and the initial conditiond y0.\n */\n\n unsigned int steps = 100;\n unsigned int time = 20;\n\n auto f = [] (Eigen::VectorXd y) {\n Eigen::VectorXd df(2);\n df << y(0)*(3-0.7*y(1)) , -y(1)*(0.7-0.8*y(0));\n return df;\n };\n\n Eigen::VectorXd y0(2);\n y0 << 6,2;\n\n /**\n * Solve using built in solver:\n */\n\n std::vector y1Vec = ExplicitRKSolvers::classical4thOrderRuleIntegrator(f, time,y0, steps);\n\n std::cout << \"The classical 4th order Runge-Kutta method gives us\" << y1Vec.back().transpose() << std::endl;\n\n for(int i = 0; i < y1Vec.size(); i++){\n std::cout << y1Vec.at(i).transpose() << \" \\n\";\n }\n\n /**\n * Solve explicitly using custom Butcher's table:\n */\n\n Eigen::MatrixXd A(3,3);\n A << 0, 0, 0,\n 1, 0, 0,\n 1.0/4,1.0/4,0;\n Eigen::VectorXd b(3);\n b << 1.0/6, 1.0/6, 2.0/3;\n\n ExplicitRungeKuttaIntegrator Solver(A,b);\n std::vector y2Vec = Solver.solve(f,2,y0,10);\n\n std::cout << \"SSPRK3 3rd order Runge-Kutta method gives us = \" << y2Vec[10].transpose() << std::endl;\n \n}\n\n \n", "meta": {"hexsha": "c1ba309930b8577b6e8ca6b5620a1f170ce33bba", "size": 1404, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "usage.cpp", "max_stars_repo_name": "davidrzs/Runge-Kutta-ODE-Solver", "max_stars_repo_head_hexsha": "d6295007e78ae390ff95e2c25e4bcc906ce9624e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "usage.cpp", "max_issues_repo_name": "davidrzs/Runge-Kutta-ODE-Solver", "max_issues_repo_head_hexsha": "d6295007e78ae390ff95e2c25e4bcc906ce9624e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "usage.cpp", "max_forks_repo_name": "davidrzs/Runge-Kutta-ODE-Solver", "max_forks_repo_head_hexsha": "d6295007e78ae390ff95e2c25e4bcc906ce9624e", "max_forks_repo_licenses": ["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.6451612903, "max_line_length": 110, "alphanum_fraction": 0.6054131054, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7598193634737237}} {"text": "#include \n#include \n\narma::mat CENTERS = {20.0, 35.0, 40.0, 45.0};\narma::mat SIGMAS = {3.0, 10.0, 5.0, 2.0};\narma::mat CHANNELS = arma::linspace(0, 99, 100);\n\nconst double EulerConstant = std::exp(1.0);\n\nclass DataGenerator\n{\n\npublic:\n arma::mat m_L;\n\n DataGenerator()\n {\n m_L = generate_library();\n }\n\n arma::mat generate_library(arma::mat channels = CHANNELS,\n arma::mat centers = CENTERS,\n arma::mat sigmas = SIGMAS)\n {\n return generate_signal_matrix(channels, centers, sigmas);\n };\n\n arma::mat generate_signal(arma::mat weights, double noise = 0.00, double offset = 0.0)\n {\n arma::mat signal = get_linear_signal(weights);\n return signal + noise * arma::randn(1, signal.n_elem) + offset;\n }\n\n arma::mat generate_signal(arma::mat weights,\n std::vector indices,\n double outlier_sigma_square = 10,\n double outlier_offset = 0.0,\n double noise = 0.00,\n double offset = 0.00)\n {\n arma::mat signal = get_linear_signal(weights);\n std::default_random_engine generator;\n std::normal_distribution distribution(outlier_offset, outlier_sigma_square);\n for (auto &&i : indices)\n {\n signal[i] += distribution(generator);\n }\n return signal + noise * arma::randn(1, signal.n_elem) + offset;\n }\n\n template \n arma::mat generate_signal(arma::mat weights, arma::mat library, Function model, double noise = 0.0, double offset = 0.0)\n {\n arma::mat signal = model(weights, library);\n return signal + noise * arma::randn(1, signal.n_elem) + offset;\n }\n\nprivate:\n arma::mat generate_signal_matrix(arma::mat channels, arma::mat centers, arma::mat sigmas)\n {\n int n_components = centers.n_elem;\n arma::mat signals = arma::zeros(0, channels.n_elem);\n for (int i = 0; i < n_components; ++i)\n {\n float center = centers[i];\n float sigma = sigmas[i];\n arma::mat signal = calculate_gaussian(sigma, center, channels);\n signals = join_vert(signals, signal.t());\n };\n return signals;\n }\n\n arma::mat get_linear_signal(arma::mat x)\n {\n return x * m_L;\n }\n\n arma::mat calculate_gaussian(float sigma, float center, arma::mat x)\n {\n float scaling_factor = 1 / (sigma * sqrt(2 * M_PI));\n arma::mat exponent = -pow((x - center) / sigma, 2) / 2;\n arma::mat result = scaling_factor * pow_to_vector(EulerConstant, exponent);\n return result;\n }\n\n arma::mat pow_to_vector(float x, arma::mat y)\n {\n arma::mat result;\n result.copy_size(y);\n for (std::size_t i = 0; i < result.n_elem; ++i)\n {\n result[i] = std::pow(x, y[i]);\n }\n return result;\n }\n};\n", "meta": {"hexsha": "ac8f4326b31d3f6c8065e7bfe173365d13aa604a", "size": 3020, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "samples/utils/data_generator.cpp", "max_stars_repo_name": "omyllymaki/math", "max_stars_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-11-04T03:43:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T09:12:24.000Z", "max_issues_repo_path": "samples/utils/data_generator.cpp", "max_issues_repo_name": "omyllymaki/math", "max_issues_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "samples/utils/data_generator.cpp", "max_forks_repo_name": "omyllymaki/math", "max_forks_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1340206186, "max_line_length": 124, "alphanum_fraction": 0.5609271523, "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7593184447064062}} {"text": "#include \n#include \n#include \n#include \n#include \nusing namespace Eigen;\nusing namespace std;\n\nstruct EulerAngle {\n EulerAngle()\n {\n roll_ = 0.;\n pitch_ = 0.;\n yaw_ = 0.;\n }\npublic:\n double roll_;\n double pitch_;\n double yaw_;\n};\n\nstd::ostream& operator<<(std::ostream& os, const EulerAngle& o)\n{\n // yaw-pitch-roll => ZYX\n os << o.yaw_ << \" \" << o.pitch_ << \" \" << o.roll_;\n return os;\n}\n\nstd::istream& operator>>(std::istream& is, EulerAngle& o)\n{\n is >> o.yaw_;\n is >> o.pitch_;\n is >> o.roll_;\n return is;\n}\n\npangolin::Var* eulerAngle;\n\nstruct RotationMatrix {\n Matrix3d matrix = Matrix3d::Identity();\n};\n\nostream& operator<<(ostream& out, const RotationMatrix& r)\n{\n out.setf(ios::fixed);\n Matrix3d matrix = r.matrix;\n out << '=';\n out << \"[\" << setprecision(2) << matrix(0, 0) << \",\" << matrix(0, 1) << \",\" << matrix(0, 2) << \"],\"\n << \"[\" << matrix(1, 0) << \",\" << matrix(1, 1) << \",\" << matrix(1, 2) << \"],\"\n << \"[\" << matrix(2, 0) << \",\" << matrix(2, 1) << \",\" << matrix(2, 2) << \"]\";\n return out;\n}\n\nistream& operator>>(istream& in, RotationMatrix& r)\n{\n return in;\n}\n\nstruct QuaternionDraw {\n Quaterniond q;\n};\n\nostream& operator<<(ostream& out, const QuaternionDraw quat)\n{\n auto c = quat.q.coeffs();\n out << \"=[\" << c[0] << \",\" << c[1] << \",\" << c[2] << \",\" << c[3] << \"]\";\n return out;\n}\n\nistream& operator>>(istream& in, const QuaternionDraw quat)\n{\n return in;\n}\n\nvoid ResetCallback()\n{\n std::cout << \"You typed ctrl-r or pushed reset\" << std::endl;\n EulerAngle ea;\n *eulerAngle = ea;\n}\n\nEigen::Quaterniond euler2Quaternion(const double yaw, const double pitch, const double roll)\n{\n Eigen::AngleAxisd rollAngle(roll, Eigen::Vector3d::UnitX());\n Eigen::AngleAxisd pitchAngle(pitch, Eigen::Vector3d::UnitY());\n Eigen::AngleAxisd yawAngle(yaw, Eigen::Vector3d::UnitZ());\n\n Eigen::Quaterniond q = yawAngle * pitchAngle * rollAngle;\n return q;\n}\n\nint main(int argc, char** argv)\n{\n const int UI_WIDTH = 500;\n pangolin::CreateWindowAndBind(\"visualize geometry\", 1000, 500);\n glEnable(GL_DEPTH_TEST);\n // OpenGlMatrixSpec pangolin::ProjectionMatrix(int w, int h, double fu, double fv, double u0, double v0, double zNear, double zFar);\n //OpenGlMatrix \tModelViewLookAt (double ex, double ey, double ez, double lx, double ly, double lz, AxisDirection up)\n pangolin::OpenGlRenderState s_cam(\n pangolin::ProjectionMatrix(1000, 600, 420, 420, 500, 300, 0.1, 100),\n pangolin::ModelViewLookAt(3, 3, 3, 0, 0, 0, pangolin::AxisZ));\n pangolin::View& d_cam = pangolin::CreateDisplay()\n .SetBounds(0.0, 1.0, pangolin::Attach::Pix(UI_WIDTH), 1.0, -1000.0f / 600.0f)\n .SetHandler(new pangolin::Handler3D(s_cam));\n // ui\n pangolin::CreatePanel(\"ui\").SetBounds(0.0, 1.0, 0.0, pangolin::Attach::Pix(UI_WIDTH));\n eulerAngle = new pangolin::Var(\"ui.YawPitchRoll\", EulerAngle());\n pangolin::Var rotation_matrix(\"ui.R\", RotationMatrix());\n pangolin::Var quaternion(\"ui.Quaternion\", QuaternionDraw());\n pangolin::Var> reset(\"ui.Reset\", ResetCallback);\n\n while (!pangolin::ShouldQuit()) {\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n d_cam.Activate(s_cam);\n\n // input eulerangle\n EulerAngle ea = *eulerAngle;\n cout << \"yaw: \" << ea.yaw_ << \"\\t pitch: \" << ea.pitch_ << \"\\troll: \" << ea.roll_ << endl;\n\n // Eulerangle to quaterniond\n Eigen::Quaterniond qd = euler2Quaternion(ea.yaw_ / 180 * M_PI, ea.pitch_ / 180 * M_PI, ea.roll_ / 180 * M_PI);\n\n // show quaternion\n QuaternionDraw quat;\n quat.q = qd;\n quaternion = quat;\n\n // quaterniond to rotationmatrix\n Matrix3d rot = qd.toRotationMatrix();\n\n // pangolin::OpenGlMatrix matrix = s_cam.GetModelViewMatrix();\n RotationMatrix R;\n for (int i = 0; i < 3; i++)\n for (int j = 0; j < 3; j++)\n R.matrix(i, j) = rot(j, i);\n rotation_matrix = R;\n // transform matrix for pangolin\n Matrix matrix;\n for (int i = 0; i < 3; i++)\n for (int j = 0; j < 3; j++)\n matrix(i, j) = rot(j, i);\n\n s_cam.SetModelViewMatrix(pangolin::OpenGlMatrix(matrix));\n\n pangolin::glDrawColouredCube();\n\n // draw the original axis\n glLineWidth(3);\n glColor3f(0.8f, 0.f, 0.f);\n glBegin(GL_LINES);\n glVertex3f(0, 0, 0);\n glVertex3f(10, 0, 0);\n glColor3f(0.f, 0.8f, 0.f);\n glVertex3f(0, 0, 0);\n glVertex3f(0, 10, 0);\n glColor3f(0.2f, 0.2f, 1.f);\n glVertex3f(0, 0, 0);\n glVertex3f(0, 0, 10);\n glEnd();\n\n pangolin::FinishFrame();\n }\n\n return 0;\n}\n", "meta": {"hexsha": "fdf85d73b4adfbaa821841554792eb96e92b16fa", "size": 4977, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "yubaoliu/VisualizeGeometry", "max_stars_repo_head_hexsha": "4a58ffd1d68d5cb2d12012af00c00743dbee8327", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T06:55:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-23T03:01:04.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "yubaoliu/VisualizeGeometry", "max_issues_repo_head_hexsha": "4a58ffd1d68d5cb2d12012af00c00743dbee8327", "max_issues_repo_licenses": ["MIT"], "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": "yubaoliu/VisualizeGeometry", "max_forks_repo_head_hexsha": "4a58ffd1d68d5cb2d12012af00c00743dbee8327", "max_forks_repo_licenses": ["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.9819277108, "max_line_length": 136, "alphanum_fraction": 0.5810729355, "num_tokens": 1501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7591560355426781}} {"text": "//\n// Copyright © 2017 Arm Ltd. All rights reserved.\n// See LICENSE file in the project root for full license information.\n//\n\n#include \"Activation.hpp\"\n\n#include \n\n#include \n\nnamespace armnn\n{\n\nvoid Activation(const float* in,\n float* out,\n const TensorInfo& tensorInfo,\n ActivationFunction function,\n float a,\n float b)\n{\n for (size_t i = 0; i 0.0f ? input : (input * a);\n break;\n }\n case ActivationFunction::Abs:\n {\n output = input < 0 ? -input : input;\n break;\n }\n case ActivationFunction::Sqrt:\n {\n output = sqrtf(input);\n break;\n }\n case ActivationFunction::Square:\n {\n output = input * input;\n break;\n }\n case ActivationFunction::TanH:\n {\n output = a * tanhf(b * input);\n break;\n }\n default:\n {\n BOOST_LOG_TRIVIAL(error) << \"Unsupported activation function\";\n return;\n }\n }\n\n out[i] = output;\n }\n}\n\n} //namespace armnn\n", "meta": {"hexsha": "ede283cbf9db28eb8819397268200a8911d6b952", "size": 2303, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/armnn/backends/RefWorkloads/Activation.cpp", "max_stars_repo_name": "Air000/armnn_s32v", "max_stars_repo_head_hexsha": "ec3ee60825d6b7642a70987c4911944cef7a3ee6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-19T08:44:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-19T08:44:28.000Z", "max_issues_repo_path": "src/armnn/backends/RefWorkloads/Activation.cpp", "max_issues_repo_name": "Air000/armnn_s32v", "max_issues_repo_head_hexsha": "ec3ee60825d6b7642a70987c4911944cef7a3ee6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/armnn/backends/RefWorkloads/Activation.cpp", "max_forks_repo_name": "Air000/armnn_s32v", "max_forks_repo_head_hexsha": "ec3ee60825d6b7642a70987c4911944cef7a3ee6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-11T05:58:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-11T05:58:56.000Z", "avg_line_length": 25.0326086957, "max_line_length": 78, "alphanum_fraction": 0.4290056448, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7591560265821635}} {"text": "/**\n *\n * @section DESCRIPTION\n *\n * Recursive Exponentiation.\n *\n * Write a recursive function power(base, exponent) that, when invoked, returns\n *\n * baseexponent\n *\n * For example, power(3, 4) = 3 * 3 * 3 * 3. Assume that exponent is an integer\n * greater than or equal to 1. Hint: The recursion step would use the\n * relationship\n *\n * baseexponent = base * baseexponent - 1\n *\n * and the terminating condition occurs when exponent is equal to 1, because\n *\n * base1 = base\n */\n\n#include \n#include \n#include \n\nusing boost::multiprecision::checked_cpp_int;\n\nstatic checked_cpp_int\nPower(const checked_cpp_int &base, const checked_cpp_int &exponent)\n{\n assert(base >= 0 && exponent > 0);\n\n if (exponent == 1) {\n return base;\n }\n return base * Power(base, exponent - 1);\n}\n\nint main(void)\n{\n using namespace std;\n\n checked_cpp_int base, exponent;\n\n cout << \"Enter base: \";\n cin >> base;\n cout << \"Enter exponent: \";\n cin >> exponent;\n cout \\\n << \"Power(\" << base << \", \" << exponent << \") = \"\n << Power(base, exponent) << endl;\n return 0;\n}\n", "meta": {"hexsha": "fa344cb07d3313e05b9bb69e7d05dba9e797e03e", "size": 1152, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/6/exercises/6-36.cpp", "max_stars_repo_name": "jhxie/CPlusPlusHowToProgram", "max_stars_repo_head_hexsha": "a622902a9e5e9766d9ddb83a38070d57dba786c3", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-10T03:32:46.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-10T03:32:46.000Z", "max_issues_repo_path": "src/6/exercises/6-36.cpp", "max_issues_repo_name": "jhxie/CPlusPlusHowToProgram", "max_issues_repo_head_hexsha": "a622902a9e5e9766d9ddb83a38070d57dba786c3", "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/6/exercises/6-36.cpp", "max_forks_repo_name": "jhxie/CPlusPlusHowToProgram", "max_forks_repo_head_hexsha": "a622902a9e5e9766d9ddb83a38070d57dba786c3", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3333333333, "max_line_length": 79, "alphanum_fraction": 0.6345486111, "num_tokens": 301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.758875144280419}} {"text": "/**\n * \\file boost/numeric/ublasx/operation/hild.hpp\n *\n * \\brief Hilbert matrix.\n *\n * Copyright (c) 2012, Marco Guazzone\n * \n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_HILB_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_HILB_HPP\n\n\n#include \n#include \n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\ntemplate \nBOOST_UBLAS_INLINE\nmatrix hilb(::std::size_t n)\n{\n\tmatrix H(n,n);\n\n\tfor (::std::size_t r = 0; r < n; ++r)\n\t{\n\t\tfor (::std::size_t c = 0; c < n; ++c)\n\t\t{\n\t\t\t//H(r,c) = T(1.0)/((r+1)+(c+1)-T(1.0));\n\t\t\tH(r,c) = T(1.0)/(r+c+T(1.0));\n\t\t}\n\t}\n\n\treturn H;\n}\n\n\nBOOST_UBLAS_INLINE\nmatrix hilb(::std::size_t n, int=0)\n{\n\treturn hilb(n);\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_HILB_HPP\n", "meta": {"hexsha": "21d573aa1087eeeb5f457dda74b9a0dcb379c72e", "size": 1100, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/hilb.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/hilb.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/hilb.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": 19.6428571429, "max_line_length": 66, "alphanum_fraction": 0.6781818182, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.7588403455205481}} {"text": "#include \n#include \n\n#include \n#include \"mathutils/matrix_tool.hh\"\n#include \"mathutils/numerical_constants.hh\"\n\narma::vec3 pol_from_cart(arma::vec3 in)\n{\n double d = 0.0;\n double azimuth = 0.0;\n double elevation = 0.0;\n double denom;\n arma::vec3 POLAR;\n\n double v1 = in(0);\n double v2 = in(1);\n double v3 = in(2);\n\n d = norm(in);\n azimuth = atan2(v2, v1);\n\n denom = sqrt(v1 * v1 + v2 * v2);\n if (denom > 0.) {\n elevation = atan2(-v3, denom);\n } else {\n if (v3 > 0)\n elevation = -PI / 2.;\n if (v3 < 0)\n elevation = PI / 2.;\n if (v3 == 0)\n elevation = 0.;\n }\n\n POLAR(0) = d;\n POLAR(1) = azimuth;\n POLAR(2) = elevation;\n\n return POLAR;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// Returns the angle between two 3x1 vectors\n// Example: theta=angle(VEC1,VEC2);\n// 010824 Created by Peter H Zipfel\n///////////////////////////////////////////////////////////////////////////////\ndouble angle(arma::vec3 VEC1, arma::vec3 VEC2)\n{\n double argument;\n double scalar = dot(VEC1, VEC2);\n double abs1 = norm(VEC1);\n double abs2 = norm(VEC2);\n\n double dum = abs1 * abs2;\n if (abs1 * abs2 > arma::datum::eps)\n argument = scalar / dum;\n else\n argument = 1.;\n if (argument > 1.)\n argument = 1.;\n if (argument < -1.)\n argument = -1.;\n\n return acos(argument);\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// Return skew symmetric matrix of a Vector3\n// | 0 -c b| |a|\n// | c 0 -a| <-- |b|\n// |-b a 0| |c|\n//\n// Example: MAT = VEC.skew_sym();\n///////////////////////////////////////////////////////////////////////////////\narma::mat33 skew_sym(arma::vec3 vec)\n{\n arma::mat33 RESULT;\n\n RESULT(0, 0) = 0;\n RESULT(1, 0) = vec(2);\n RESULT(2, 0) = -vec(1);\n RESULT(0, 1) = -vec(2);\n RESULT(1, 1) = 0;\n RESULT(2, 1) = vec(0);\n RESULT(0, 2) = vec(1);\n RESULT(1, 2) = -vec(0);\n RESULT(2, 2) = 0;\n\n return RESULT;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Returns the T.M. of the psivg -> thtvg sequence\n//\n// 010628 Created by Peter H Zipfel\n// 170121 Create Armadillo Version by soncyang\n////////////////////////////////////////////////////////////////////////////////\narma::mat33 build_psivg_thtvg_TM(const double &psivg, const double &thtvg)\n{\n arma::mat33 AMAT;\n\n AMAT(0, 2) = -sin(thtvg);\n AMAT(1, 0) = -sin(psivg);\n AMAT(1, 1) = cos(psivg);\n AMAT(2, 2) = cos(thtvg);\n AMAT(0, 0) = (AMAT(2, 2) * AMAT(1, 1));\n AMAT(0, 1) = (-AMAT(2, 2) * AMAT(1, 0));\n AMAT(2, 0) = (-AMAT(0, 2) * AMAT(1, 1));\n AMAT(2, 1) = (AMAT(0, 2) * AMAT(1, 0));\n AMAT(1, 2) = 0.0;\n\n return AMAT;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Returns the T.M. of the psi->tht->phi sequence\n// Euler angle transformation matrix of flight mechanics\n//\n// 011126 Created by Peter H Zipfel\n// 170121 Add Armadillo version\n////////////////////////////////////////////////////////////////////////////////\narma::mat33 build_psi_tht_phi_TM(const double &psi, const double &tht, const double &phi)\n{\n double spsi = sin(psi);\n double cpsi = cos(psi);\n double stht = sin(tht);\n double ctht = cos(tht);\n double sphi = sin(phi);\n double cphi = cos(phi);\n\n arma::mat33 AMAT;\n AMAT(0, 0) = cpsi * ctht;\n AMAT(1, 0) = cpsi * stht * sphi - spsi * cphi;\n AMAT(2, 0) = cpsi * stht * cphi + spsi * sphi;\n AMAT(0, 1) = spsi * ctht;\n AMAT(1, 1) = spsi * stht * sphi + cpsi * cphi;\n AMAT(2, 1) = spsi * stht * cphi - cpsi * sphi;\n AMAT(0, 2) = -stht;\n AMAT(1, 2) = ctht * sphi;\n AMAT(2, 2) = ctht * cphi;\n\n return AMAT;\n}\n\narma::vec4 Matrix2Quaternion(arma::mat33 Matrix_in)\n{\n arma::vec4 q_square;\n double q_square_max;\n int j;\n arma::vec4 Quaternion;\n Matrix_in = trans(Matrix_in);\n q_square[0] = fabs(1.0 + Matrix_in(0, 0) + Matrix_in(1, 1) + Matrix_in(2, 2));\n q_square[1] = fabs(1.0 + Matrix_in(0, 0) - Matrix_in(1, 1) - Matrix_in(2, 2));\n q_square[2] = fabs(1.0 - Matrix_in(0, 0) + Matrix_in(1, 1) - Matrix_in(2, 2));\n q_square[3] = fabs(1.0 - Matrix_in(0, 0) - Matrix_in(1, 1) + Matrix_in(2, 2));\n\n q_square_max = q_square.max();\n j = q_square.index_max();\n\n switch (j) {\n case 0:\n Quaternion(0) = 0.5 * sqrt(q_square_max);\n Quaternion(1) = 0.25 * (Matrix_in(2, 1) - Matrix_in(1, 2)) / Quaternion[0];\n Quaternion(2) = 0.25 * (Matrix_in(0, 2) - Matrix_in(2, 0)) / Quaternion[0];\n Quaternion(3) = 0.25 * (Matrix_in(1, 0) - Matrix_in(0, 1)) / Quaternion[0];\n break;\n case 1:\n Quaternion(1) = 0.5 * sqrt(q_square_max);\n Quaternion(0) = 0.25 * (Matrix_in(2, 1) - Matrix_in(1, 2)) / Quaternion[1];\n Quaternion(2) = 0.25 * (Matrix_in(1, 0) + Matrix_in(0, 1)) / Quaternion[1];\n Quaternion(3) = 0.25 * (Matrix_in(0, 2) + Matrix_in(2, 0)) / Quaternion[1];\n break;\n case 2:\n Quaternion(2) = 0.5 * sqrt(q_square_max);\n Quaternion(0) = 0.25 * (Matrix_in(0, 2) - Matrix_in(2, 0)) / Quaternion[2];\n Quaternion(1) = 0.25 * (Matrix_in(1, 0) + Matrix_in(0, 1)) / Quaternion[2];\n Quaternion(3) = 0.25 * (Matrix_in(2, 1) + Matrix_in(1, 2)) / Quaternion[2];\n break;\n case 3:\n Quaternion(3) = 0.5 * sqrt(q_square_max);\n Quaternion(0) = 0.25 * (Matrix_in(1, 0) - Matrix_in(0, 1)) / Quaternion[3];\n Quaternion(1) = 0.25 * (Matrix_in(2, 0) + Matrix_in(0, 2)) / Quaternion[3];\n Quaternion(2) = 0.25 * (Matrix_in(2, 1) + Matrix_in(1, 2)) / Quaternion[3];\n break;\n }\n\n return Quaternion;\n}\n\narma::mat33 Quaternion2Matrix(arma::vec4 Quaternion_in)\n{\n arma::mat33 Matrix_out;\n\n Matrix_out(0, 0) = 2. * (Quaternion_in(0) * Quaternion_in(0) + Quaternion_in(1) * Quaternion_in(1)) - 1.;\n Matrix_out(0, 1) = 2. * (Quaternion_in(1) * Quaternion_in(2) + Quaternion_in(0) * Quaternion_in(3));\n Matrix_out(0, 2) = 2. * (Quaternion_in(1) * Quaternion_in(3) - Quaternion_in(0) * Quaternion_in(2));\n Matrix_out(1, 0) = 2. * (Quaternion_in(1) * Quaternion_in(2) - Quaternion_in(0) * Quaternion_in(3));\n Matrix_out(1, 1) = 2. * (Quaternion_in(0) * Quaternion_in(0) + Quaternion_in(2) * Quaternion_in(2)) - 1.;\n Matrix_out(1, 2) = 2. * (Quaternion_in(2) * Quaternion_in(3) + Quaternion_in(0) * Quaternion_in(1));\n Matrix_out(2, 0) = 2. * (Quaternion_in(1) * Quaternion_in(3) + Quaternion_in(0) * Quaternion_in(2));\n Matrix_out(2, 1) = 2. * (Quaternion_in(2) * Quaternion_in(3) - Quaternion_in(0) * Quaternion_in(1));\n Matrix_out(2, 2) = 2. * (Quaternion_in(0) * Quaternion_in(0) + Quaternion_in(3) * Quaternion_in(3)) - 1.;\n\n return Matrix_out;\n}\n\narma::vec4 Quaternion_conjugate(arma::vec4 Quaternion_in)\n{\n arma::vec4 Quaternion_out;\n\n Quaternion_out(0) = Quaternion_in(0);\n Quaternion_out(1) = -Quaternion_in(1);\n Quaternion_out(2) = -Quaternion_in(2);\n Quaternion_out(3) = -Quaternion_in(3);\n\n return Quaternion_out;\n}\n\narma::vec4 Quaternion_cross(arma::vec4 Quaternion_in1, arma::vec4 Quaternion_in2)\n{\n arma::vec4 Quaternion_out;\n\n Quaternion_out(0) = Quaternion_in1(0) * Quaternion_in2(0) - Quaternion_in1(1) * Quaternion_in2(1) - Quaternion_in1(2) * Quaternion_in2(2) - Quaternion_in1(3) * Quaternion_in2(3);\n Quaternion_out(1) = Quaternion_in1(1) * Quaternion_in2(0) + Quaternion_in1(0) * Quaternion_in2(1) - Quaternion_in1(3) * Quaternion_in2(2) + Quaternion_in1(2) * Quaternion_in2(3);\n Quaternion_out(2) = Quaternion_in1(2) * Quaternion_in2(0) + Quaternion_in1(3) * Quaternion_in2(1) + Quaternion_in1(0) * Quaternion_in2(2) - Quaternion_in1(1) * Quaternion_in2(3);\n Quaternion_out(3) = Quaternion_in1(3) * Quaternion_in2(0) - Quaternion_in1(2) * Quaternion_in2(1) + Quaternion_in1(1) * Quaternion_in2(2) + Quaternion_in1(0) * Quaternion_in2(3);\n\n return Quaternion_out;\n}\n\nvoid Quaternion2Euler(arma::vec4 Quaternion_in, double &Roll, double &Pitch, double &Yaw)\n{\n Roll = atan2(2.0 * (Quaternion_in(0) * Quaternion_in(1) + Quaternion_in(2) * Quaternion_in(3)), 1.0 - 2.0 * (Quaternion_in(1) * Quaternion_in(1) + Quaternion_in(2) * Quaternion_in(2)));\n Pitch = asin(2.0 * (Quaternion_in(0) * Quaternion_in(2) - Quaternion_in(3) * Quaternion_in(1)));\n Yaw = atan2(2.0 * (Quaternion_in(0) * Quaternion_in(3) + Quaternion_in(1) * Quaternion_in(2)), 1.0 - 2.0 * (Quaternion_in(2) * Quaternion_in(2) + Quaternion_in(3) * Quaternion_in(3)));\n}\n\narma::vec4 Euler2Quaternion(double Roll, double Pitch, double Yaw)\n{\n arma::vec4 Quaternion_out;\n double cr = cos(Roll * 0.5);\n double sr = sin(Roll * 0.5);\n double cp = cos(Pitch * 0.5);\n double sp = sin(Pitch * 0.5);\n double cy = cos(Yaw * 0.5);\n double sy = sin(Yaw * 0.5);\n\n Quaternion_out(0) = cy * cr * cp + sy * sr * sp;\n Quaternion_out(1) = cy * sr * cp - sy * cr * sp;\n Quaternion_out(2) = cy * cr * sp + sy * sr * cp;\n Quaternion_out(3) = sy * cr * cp - cy * sr * sp;\n\n return Quaternion_out;\n}\n\nint QuaternionMultiply(arma::vec4 &Q_out, arma::vec4 const &Q_in1, arma::vec4 const &Q_in2)\n{\n //Q_in1.print(\"Qin1:%5.5lf\");\n //Q_in2.print(\"Qin2:%5.5lf\");\n Q_out(0) = Q_in1(0) * Q_in2(0) - Q_in1(1) * Q_in2(1) - Q_in1(2) * Q_in2(2) - Q_in1(3) * Q_in2(3);\n Q_out(1) = Q_in1(0) * Q_in2(1) + Q_in1(1) * Q_in2(0) + Q_in1(2) * Q_in2(3) - Q_in1(3) * Q_in2(2);\n Q_out(2) = Q_in1(0) * Q_in2(2) - Q_in1(1) * Q_in2(3) + Q_in1(2) * Q_in2(0) + Q_in1(3) * Q_in2(1);\n Q_out(3) = Q_in1(0) * Q_in2(3) + Q_in1(1) * Q_in2(2) - Q_in1(2) * Q_in2(1) + Q_in1(3) * Q_in2(0);\n //Q_out.print(\"Qout2:%5.5lf\");\n return 0;\n}\n\narma::vec4 QuaternionInverse(arma::vec4 Q_in)\n{\n return Quaternion_conjugate(Q_in) / sqrt(Q_in(0) * Q_in(0) + Q_in(1) * Q_in(1) + Q_in(2) * Q_in(2) + Q_in(3) * Q_in(3));\n}\n\narma::vec4 QuaternionTranspose(arma::vec4 Q_in)\n{\n arma::vec4 Q_out;\n\n Q_out(0) = -Q_in(0);\n Q_out(1) = Q_in(1);\n Q_out(2) = Q_in(2);\n Q_out(3) = Q_in(3);\n\n return Q_out;\n}\n\narma::vec3 QuaternionRotation(arma::vec4 Q_in, arma::vec3 V_in)\n{\n arma::vec4 Q_temp;\n arma::vec3 V_out;\n\n Q_temp(0) = 0.0;\n Q_temp(1) = V_in(0);\n Q_temp(2) = V_in(1);\n Q_temp(3) = V_in(2);\n\n Q_temp = Quaternion_cross(Quaternion_conjugate(Q_in), Quaternion_cross(Q_temp, Q_in));\n\n V_out(0) = Q_temp(1);\n V_out(1) = Q_temp(2);\n V_out(2) = Q_temp(3);\n\n return V_out;\n}\n\narma::mat33 cross_matrix(arma::vec3 in)\n{\n arma::mat33 c_matrix;\n\n c_matrix(0, 0) = 0.0;\n c_matrix(0, 1) = -in(2);\n c_matrix(0, 2) = in(1);\n c_matrix(1, 0) = in(2);\n c_matrix(1, 1) = 0.0;\n c_matrix(1, 2) = -in(0);\n c_matrix(2, 0) = -in(1);\n c_matrix(2, 1) = in(0);\n c_matrix(2, 2) = 0.0;\n\n return c_matrix;\n}\n\narma::mat33 TMX(double ang)\n{\n arma::mat33 TM;\n\n TM(0, 0) = 1.0;\n TM(0, 1) = 0.0;\n TM(0, 2) = 0.0;\n TM(1, 0) = 0.0;\n TM(1, 1) = cos(ang);\n TM(1, 2) = sin(ang);\n TM(2, 0) = 0.0;\n TM(2, 1) = -sin(ang);\n TM(2, 2) = cos(ang);\n\n return TM;\n}\n\narma::mat33 TMY(double ang)\n{\n arma::mat33 TM;\n\n TM(0, 0) = cos(ang);\n TM(0, 1) = 0.0;\n TM(0, 2) = -sin(ang);\n TM(1, 0) = 0.0;\n TM(1, 1) = 1.0;\n TM(1, 2) = 0.0;\n TM(2, 0) = sin(ang);\n TM(2, 1) = 0.0;\n TM(2, 2) = cos(ang);\n\n return TM;\n}\n\narma::mat33 TMZ(double ang)\n{\n arma::mat33 TM;\n\n TM(0, 0) = cos(ang);\n TM(0, 1) = sin(ang);\n TM(0, 2) = 0.0;\n TM(1, 0) = -sin(ang);\n TM(1, 1) = cos(ang);\n TM(1, 2) = 0.0;\n TM(2, 0) = 0.0;\n TM(2, 1) = 0.0;\n TM(2, 2) = 1.0;\n\n return TM;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// Returns the sign of the variable\n// Example: value_signed=value*sign(variable)\n// 010824 Created by Peter H Zipfel\n///////////////////////////////////////////////////////////////////////////////\nint sign(const double &variable)\n{\n int sign = 0;\n if (variable < 0.)\n sign = -1;\n if (variable >= 0.)\n sign = 1;\n\n return sign;\n}\n\narma::vec3 euler_angle(arma::mat33 TBD_in)\n{\n double psibdc(0), thtbdc(0), phibdc(0);\n double cthtbd(0);\n\n double mroll = 0;\n\n double tbd13 = TBD_in(0, 2);\n double tbd11 = TBD_in(0, 0);\n double tbd33 = TBD_in(2, 2);\n double tbd12 = TBD_in(0, 1);\n double tbd23 = TBD_in(1, 2);\n\n arma::vec3 euler_ang;\n // *geodetic Euler angles\n // computed pitch angle: 'thtbdc'\n // note: when |tbd13| >= 1, thtbdc = +- pi/2, but cos(thtbdc) is\n // forced to be a small positive number to prevent division by zero\n if (fabs(tbd13) < 1) {\n thtbdc = asin(-tbd13);\n cthtbd = cos(thtbdc);\n } else {\n thtbdc = PI / 2 * sign(-tbd13);\n cthtbd = EPS;\n }\n // computed yaw angle: 'psibdc'\n double cpsi = tbd11 / cthtbd;\n if (fabs(cpsi) > 1)\n cpsi = 1 * sign(cpsi);\n psibdc = acos(cpsi) * sign(tbd12);\n\n // computed roll angle: 'phibdc'\n double cphi = tbd33 / cthtbd;\n if (fabs(cphi) > 1)\n cphi = 1 * sign(cphi);\n\n // selecting the Euler roll angle of flight mechanics (not for thtbdc=90 or\n // =-90deg)\n if (mroll == 0 || mroll == 1)\n // roll feedback for right side up\n phibdc = acos(cphi) * sign(tbd23);\n else if (mroll == 2)\n // roll feedback for inverted flight\n phibdc = acos(-cphi) * sign(-tbd23);\n\n euler_ang(0) = phibdc;\n euler_ang(1) = thtbdc;\n euler_ang(2) = psibdc;\n\n return euler_ang;\n}", "meta": {"hexsha": "d758d8c337b6798c9c2e5eccd33b2de86dbf8cdd", "size": 13605, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/libmathutils/src/matrix_tool.cpp", "max_stars_repo_name": "mlouielu/mazu-sim", "max_stars_repo_head_hexsha": "fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-26T07:09:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-26T07:09:54.000Z", "max_issues_repo_path": "modules/libmathutils/src/matrix_tool.cpp", "max_issues_repo_name": "mlouielu/mazu-sim", "max_issues_repo_head_hexsha": "fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/libmathutils/src/matrix_tool.cpp", "max_forks_repo_name": "mlouielu/mazu-sim", "max_forks_repo_head_hexsha": "fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225", "max_forks_repo_licenses": ["BSD-3-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.0616438356, "max_line_length": 189, "alphanum_fraction": 0.5453877251, "num_tokens": 4925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235896, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7585604293708786}} {"text": "// Diagonalizing tridiagonal Toeplitz matrix with Lapack functions\n// Compile as c++ -O3 -o Tridiag.x TridiagToeplitz.cpp -larmadillo -llapack -lblas\n// Here we add the harmonic oscillator to the tridiagonal Toeplitz matrix and \n// use Richardson's extrapolation scheme to obtain results to high precision\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace arma;\ndouble potential(double);\nvoid PolynomialInterpolation(vec, vec, int, double, double *, double *);\n// Begin of main program \n\nint main(int argc, char* argv[])\n{\n int i, j, StartDim, Dim;\n double RMin, RMax, Step, DiagConst, NondiagConst; \n double error, FinalE;\n RMin = 0.0; RMax = 10.0; StartDim =400;\n vec StepSizes = zeros(5); \n mat EigvaluesInterpol = zeros(5,20); \n for (int interpolation = 0; interpolation < 5; interpolation++){\n if (interpolation == 1) {\n Dim = StartDim;\n }\n else{\n Dim = (interpolation-1)*2*StartDim;\n } \n mat Hamiltonian = zeros(Dim,Dim);\n // Integration step length\n Step = RMax/Dim;\n DiagConst = 2.0 / (Step*Step);\n NondiagConst = -1.0 / (Step*Step);\n // local memory for r and the potential w[r] \n double r;\n vec Potential = zeros(Dim);\n for(i = 0; i < Dim; i++) {\n r = RMin + (i+1) * Step;\n Potential[i] = potential(r);\n }\n StepSizes(interpolation) = Step;\n // Setting up tridiagonal matrix and diagonalization using Armadillo\n Hamiltonian(0,0) = DiagConst+Potential(0);\n Hamiltonian(0,1) = NondiagConst;\n for(i = 1; i < Dim-1; i++) {\n Hamiltonian(i,i-1) = NondiagConst;\n Hamiltonian(i,i) = DiagConst+Potential(i);\n Hamiltonian(i,i+1) = NondiagConst;\n }\n Hamiltonian(Dim-1,Dim-2) = NondiagConst;\n Hamiltonian(Dim-1,Dim-1) = DiagConst+Potential(Dim-1);\n // diagonalize and obtain eigenvalues\n vec Eigval(Dim);\n eig_sym(Eigval, Hamiltonian);\n for (int l = 0; l < 20; l++){\n // EigvaluesInterpol(interpolation,l) = Eigval(l);\n vec EigSend(interpolation);\n for (int k = 0; k < interpolation; k++) EigSend(k) = EigvaluesInterpol(k,l);\n if (interpolation > 0 ){\n\t PolynomialInterpolation(StepSizes, EigSend, interpolation, 0.0, &FinalE, &error);\n\t cout << setiosflags(ios::showpoint | ios::uppercase);\n\tcout <<\"Eigenvalue = \" << setw(15) << l << endl; \n\tcout << setw(15) << setprecision(8) << FinalE << endl;\n }\n }\n }\n return 0;\n } // end of main function\n\n\n /*\n The function potential()\n calculates and return the value of the \n potential for a given argument x.\n The potential here is for the hydrogen atom\n */ \n\n double potential(double x)\n {\n return x*x;\n\n } // End: function potential() \n\n\n void PolynomialInterpolation(vec xa, vec ya, int n, double x, double *y, double *dy)\n {\n int i,m,ns=1;\n double den,dif,dift,ho,hp,w;\n\n dif=fabs(x-xa(0));\n vec c = zeros(n);\n vec d = zeros(n);\n for (i=0;i < n;i++) {\n if ( (dift=fabs(x-xa(i))) < dif) {\n\tns=i;\n\tdif=dift;\n }\n c(i)=ya(i);\n d(i)=ya(i);\n }\n *y=ya(ns--);\n for (m=0; m< n;m++) {\n for (i = 0;i < n-m;i++) {\n\tho=xa(i)-x;\n\thp=xa(i+m)-x;\n\tw=c(i+1)-d(i);\n\t//\t\t\tif ( (den=ho-hp) == 0.0) nrerror(\"Error \");\n\tden=w/den;\n\td(i)=hp*den;\n\tc(i)=ho*den;\n }\n *y += (*dy=(2*ns < (n-m) ? c(ns+1) : d(ns--)));\n }\n }\n\n", "meta": {"hexsha": "c4831fb4769c5c4fcb6d56b633aa0b2587bba89c", "size": 3449, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/Projects/2018/Project2/CodeExample/QDExtrapolate.cpp", "max_stars_repo_name": "kimrojas/ComputationalPhysicsMSU", "max_stars_repo_head_hexsha": "a47cfc18b3ad6adb23045b3f49fab18c0333f556", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 220.0, "max_stars_repo_stars_event_min_datetime": "2016-08-25T09:18:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:09:16.000Z", "max_issues_repo_path": "doc/Projects/2018/Project2/CodeExample/QDExtrapolate.cpp", "max_issues_repo_name": "dnhdang94/ComputationalPhysicsMSU", "max_issues_repo_head_hexsha": "16990c74cf06eb5b933982137f0536d669567259", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-04T12:55:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-04T12:55:10.000Z", "max_forks_repo_path": "doc/Projects/2018/Project2/CodeExample/QDExtrapolate.cpp", "max_forks_repo_name": "dnhdang94/ComputationalPhysicsMSU", "max_forks_repo_head_hexsha": "16990c74cf06eb5b933982137f0536d669567259", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 136.0, "max_forks_repo_forks_event_min_datetime": "2016-08-25T09:04:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T09:54:21.000Z", "avg_line_length": 28.9831932773, "max_line_length": 87, "alphanum_fraction": 0.5972745723, "num_tokens": 1116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7583969073347436}} {"text": "#pragma once\n#include \"constant_function.hpp\"\n#include \"coordinate_transform.hpp\"\n#include \"grad_shape.hpp\"\n#include \"integrate.hpp\"\n#include \"shape.hpp\"\n#include \n#include \n\n//----------------compMatrixBegin----------------\n//! Evaluate the stiffness matrix on the triangle spanned by\n//! the points (a, b, c).\n//!\n//! Here, the stiffness matrix A is a 3x3 matrix\n//!\n//! $$A_{ij} = \\int_{K} ( sigma(x,y) \\nabla \\lambda_i^K(x, y) \\cdot \\nabla \\lambda_j^K(x, y)\\; + r \\lambda_i^K(x,y)\\lambda_j^K(x,y) )dV$$\n//!\n//! where $K$ is the triangle spanned by (a, b, c).\n//!\n//! @param[out] stiffnessMatrix should be a 3x3 matrix\n//! At the end, will contain the integrals above.\n//!\n//! @param[in] a the first corner of the triangle\n//! @param[in] b the second corner of the triangle\n//! @param[in] c the third corner of the triangle\n//! @param[in] sigma the function sigma as in the exercise\n//! @param[in] r the parameter r as in the exercise\ntemplate \nvoid computeStiffnessMatrix(MatrixType & stiffnessMatrix,\n const Point &a,\n const Point &b,\n const Point &c,\n const std::function &sigma = constantFunction,\n const double r = 0) {\n\tEigen::Matrix2d coordinateTransform = makeCoordinateTransform(b - a, c - a);\n\tdouble volumeFactor = std::abs(coordinateTransform.determinant());\n\n\tEigen::Matrix2d elementMap = coordinateTransform.inverse().transpose();\n\t// (write your solution here)\n\tstiffnessMatrix.resize(3, 3);\n\n\tauto PhiK = [&](const Eigen::Vector2d &x) -> Eigen::Vector2d {\n\t\treturn coordinateTransform * x + a.transpose();\n\t};\n\n\tfor (int i = 0; i < 3; i++) {\n\t\tfor (int j = 0; j < 3; j++) {\n\t\t\tauto f = [&](double x, double y) -> double {\n\t\t\t\tEigen::Vector2d transformedPoint = PhiK(Eigen::Vector2d(x,y));\n\n\t\t\t\treturn (sigma(transformedPoint.x(), transformedPoint.y()) * (elementMap * gradientLambda(i, x, y)).dot(elementMap * gradientLambda(j, x, y)) + r * lambda(i, x, y) * lambda(j, x, y)) * volumeFactor;\n\t\t\t};\n\t\t\tstiffnessMatrix(i, j) = integrate(f);\n\t\t}\n\t}\n}\n//----------------compMatrixEnd----------------\n", "meta": {"hexsha": "857791809f4830f282f97b6b46f107850bf4ec4f", "size": 2270, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series2/2d-linFEM/stiffness_matrix.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/stiffness_matrix.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/stiffness_matrix.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": 39.1379310345, "max_line_length": 201, "alphanum_fraction": 0.6070484581, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7580786142432006}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"general_nonlinear_solver.h\" // implements general_nonlinear_solver\n\n//! \\brief Implements a single step of the modified newton\n//! \\tparam argument type of argument to function f: such as double or vector etc...\n//! \\tparam function type for the function f, likely a lambda function\n//! \\tparam jacobian type for the jacobian df, likely a lambda function\n//! \\param[in] x previous value to use in step, also initial guess if needed\n//! \\param[out] x_next next step x_{k+1} of modified Newton\n//! \\param[in] f function handle for f(x) = 0\n//! \\param[in] df function handle for jacobian df of f\ntemplate \nvoid mod_newt_step_scalar(const argument & x, argument & x_next, function&& f, jacobian&& df) {\n argument y = x + f(x) / df(x);\n x_next = y - f(y) / df(x);\n}\n\n\n//! \\brief Implements a single step of the modified newton\n//! \\tparam argument type of argument to function f: such as double or vector etc...\n//! \\tparam function type for the function f, likely a lambda function\n//! \\tparam jacobian type for the jacobian df, likely a lambda function\n//! \\param[in] x previous value to use in step, also initial guess if needed\n//! \\param[out] x_next next step x_{k+1} of modified Newton\n//! \\param[in] f function handle for f(x) = 0\n//! \\param[in] df function handle for jacobian df of f\ntemplate \nvoid mod_newt_step_system(const argument & x, argument & x_next, function&& f, jacobian&& df) {\n auto lu = df(x).lu();\n // reusing LU decomposition in the latter\n // the constructor performs LU decomposition in case argument = Vector\n argument y = x + lu.solve(f(x));\n x_next = y - lu.solve(f(y));\n}\n\n//! \\brief Solve a scalar non-linear eq. with the modified Newton\nvoid mod_newt_ord() {\n // Setting up values, functions and jacobian\n const double a = 0.123;\n auto f = [&a] (double x) { return atan(x) - a; }; // function, must see a\n auto df = [] (double x) { return 1. / (x*x+1.); };\n \n const double x_ex = tan(a); // exact solution\n \n // store solution and error at each time step\n std::vector sol;\n std::vector err;\n \n // Compute error and push back to err, used in general_nonlinear solver as breaking condition errf(x) < eps\n auto errf = [&err, x_ex] (double & x) { double e = std::abs(x - x_ex); err.push_back(e); return e; };\n \n // Perform convergence study with Modified newton for scalar\n std::cout << std::endl << \"*** Modified Newton method (scalar) ***\" << std::endl << std::endl;\n std::cout << \"Exact: \" << x_ex << std::endl;\n // Initial guess and compute initial error\n double x_scalar = 5;\n sol.push_back(x_scalar);\n errf(x_scalar);\n // Lambda performing the next step, used to define a proper function handle to be passed to general_nonlinear_solver\n auto newt_scalar_step = [&sol, &f, &df] (double x, double & x_new) { mod_newt_step_scalar(x, x_new, f, df); sol.push_back(x_new); };\n // Actually perform the solution\n general_nonlinear_solver(newt_scalar_step, x_scalar, errf);\n // Print solution (final)\n std::cout << std::endl << \"x^*_scalar = \" << std::endl << x_scalar << std::endl;\n\n // Print table of solutions, errors and EOOC\n auto space = std::setw(15);\n std::cout << std::endl << space << \"sol.\" << space << \"err.\" << space << \"order\" << std::endl;\n for(unsigned i = 0; i < sol.size(); ++ i) {\n std::cout << space << sol.at(i) << space << err.at(i);\n if(i >= 3) std::cout << space << (log(err.at(i)) - log(err.at(i-1))) / (log(err.at(i-1)) - log(err.at(i-2)));\n std::cout << std::endl;\n }\n}\n\n//! \\brief Solve a system non-linear eq. with the modified Newton\nvoid mod_newt_sys() {\n //// Setup initial values\n using Vector = Eigen::VectorXd;\n using Matrix = Eigen::MatrixXd;\n \n Matrix A = Matrix::Random(4,4);\n Vector c = Vector::Random(4);\n \n A = (A*A.transpose()).eval(); // make sure A is symmetric\n c = c.cwiseAbs(); // make sure c is > 0 uniformly\n \n // Handler for function and jacobian in standard format. Must see matrix A and vector c\n auto F = [&A,&c] (const Vector & x) { Vector tmp = A*x + c.cwiseProduct(x.array().exp().matrix()).eval(); return tmp; };\n std::function dF = [&A, &c] (const Vector & x) { Matrix C = A; Vector temp = c.cwiseProduct(x.array().exp().matrix()); C += temp.asDiagonal(); return C; };\n \n // Container for errors\n std::vector err;\n // Define lambda for breaking condition, which also stores the error of the previous step. Must see err\n auto rerr = [&err] (Vector & x) { if(err.size() > 0) return err.back(); else return 1.; };\n \n std::cout << std::endl << \"*** Modified Newton method (system) ***\" << std::endl << std::endl;\n Vector x_system = Vector::Zero(c.size()); // Initial guess\n \n // Refactor the step st. is compatible with general_nonlinear_solver, must see F; dF and error vector\n auto newt_system_step = [&F, &dF, &err] (const Vector & x, Vector & x_new) { mod_newt_step_system(x, x_new, F, dF); double e = (x - x_new).norm()/ x_new.norm(); err.push_back(e); };\n // Actually performs computations\n general_nonlinear_solver(newt_system_step, x_system, rerr);\n \n // Sanity check\n std::cout << std::endl << \"x^*_system = \" << std::endl << x_system << std::endl;\n std::cout << std::endl << \"F(x^*_system) = \" << std::endl << F(x_system) << std::endl;\n \n}\n\nint main() {\n // Part 1: solve scalar\n mod_newt_ord();\n \n // Part 2: solve system\n mod_newt_sys();\n \n}\n", "meta": {"hexsha": "32cc39986dae314da36e56c0e1c4080d2b2acf72", "size": 5758, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS5/solutions_ps5/modnewt.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS5/solutions_ps5/modnewt.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS5/solutions_ps5/modnewt.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.064, "max_line_length": 185, "alphanum_fraction": 0.641889545, "num_tokens": 1572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7579941171000275}} {"text": "/* Copyright © 2019 Apple Inc. All rights reserved.\n *\n * Use of this source code is governed by a BSD-3-clause license that can\n * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause\n */\n#include \n\nnamespace warp_perspective {\n\nEigen::MatrixXf get_2D_to_3D(int width, int height) {\n Eigen::MatrixXf A1(4,3);\n A1 << 1, 0, -1*(float)width/2, \n 0, 1, -1*(float)height/2, \n 0, 0, 1, \n 0, 0, 1;\n return A1;\n}\n\nEigen::MatrixXf get_rotation(float theta, float phi, float gamma) {\n Eigen::Matrix4f Rx, Ry, Rz, R;\n Rx << 1, 0, 0, 0,\n 0, std::cos(theta), -1*std::sin(theta), 0,\n 0, std::sin(theta), std::cos(theta), 0,\n 0, 0, 0, 1;\n Ry << std::cos(phi), 0, -1*std::sin(phi), 0,\n 0, 1, 0, 0,\n std::sin(phi), 0, std::cos(phi), 0,\n 0, 0, 0, 1;\n Rz << std::cos(gamma), -1*std::sin(gamma), 0, 0,\n std::sin(gamma), std::cos(gamma), 0, 0,\n 0, 0, 1, 0,\n 0, 0, 0, 1;\n R = (Rx * Ry) * Rz;\n return R;\n}\n\nEigen::MatrixXf get_translation(int dx, int dy, int dz) {\n Eigen::Matrix4f T;\n T << 1, 0, 0, dx,\n 0, 1, 0, dy,\n 0, 0, 1, dz,\n 0, 0, 0, 1;\n return T;\n}\n\nEigen::MatrixXf get_3D_to_2D(float focal, int width, int height) {\n Eigen::MatrixXf A2(3,4);\n A2 << focal, 0, (float)width/2, 0,\n 0, focal, (float)height/2, 0,\n 0, 0, 1, 0;\n return A2;\n}\n\nEigen::Matrix get_transformation_matrix(\n int width, int height, \n float theta, float phi, float gamma, \n int dx, int dy, int dz, \n float focal) {\n Eigen::MatrixXf A1 = get_2D_to_3D(width, height);\n Eigen::Matrix4f R = get_rotation(theta, phi, gamma);\n Eigen::Matrix4f T = get_translation(dx, dy, dz);\n Eigen::MatrixXf A2 = get_3D_to_2D(focal, width, height);\n return (A2 * (T * (R * A1)));\n}\n\n}\n", "meta": {"hexsha": "0ef52fa6ba93516ebf86b43a2500ca4acab4b17b", "size": 2041, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/image/numeric_extension/perspective_projection.hpp", "max_stars_repo_name": "jolinlaw/turicreate", "max_stars_repo_head_hexsha": "6b2057dc29533da225d18138e93cc15680eea85d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/image/numeric_extension/perspective_projection.hpp", "max_issues_repo_name": "jolinlaw/turicreate", "max_issues_repo_head_hexsha": "6b2057dc29533da225d18138e93cc15680eea85d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/image/numeric_extension/perspective_projection.hpp", "max_forks_repo_name": "jolinlaw/turicreate", "max_forks_repo_head_hexsha": "6b2057dc29533da225d18138e93cc15680eea85d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4626865672, "max_line_length": 86, "alphanum_fraction": 0.5120039196, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7579323899545048}} {"text": "#include \"writer.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n//! Vector type\ntypedef Eigen::VectorXd Vector;\n\n/// Uses forward Euler and upwind finite differences to compute u from time 0 to time T\n/// Propagation of information is assumed to be from left to right\n///\n/// @param[out] u solution at all time steps up to time T, each column corresponding to a time step (including the initial condition as first column)\n/// @param[out] time the time levels\n/// @param[in] u0 the initial conditions, as column vector\n/// @param[in] dt the time step size\n/// @param[in] T the final time at which to compute the solution (which we assume to be a multiple of dt)\n/// @param[in] N the number of grid points, INCLUDING BOUNDARY POINTS\n/// @param[in] a the advection velocity\n///\nvoid SimpleUpwindFD(Eigen::MatrixXd &u, Vector &time, const Vector u0, double dt, double T, int N, const std::function &a) {\n\tconst unsigned int nsteps = round(T / dt);\n\tconst double dx = 1. / (N - 1);\n\tu.resize(N, nsteps + 1);\n\ttime.resize(nsteps + 1);\n\n\t// (write your solution here)\n\tu.col(0) = u0;\n\ttime(0) = 0;\n\tfor (unsigned int t = 0; t < nsteps - 1; ++t) {\n\t\ttime(t + 1) = (t + 1) * dt;\n\t\tfor (int x = 1; x < N - 2; ++x) {\n\t\t\tu(x, t + 1) = u(x, t) - dt * (std::max(a(x / dx), 0.0) * (u(x, t) - u(x - 1, t)) / dx - std::min(a(x / dx), 0.0) * (u(x + 1, t) - u(x, t)) / dx);\n\t\t}\n\t\tu(0, t + 1) = u(N - 2, t + 1);\n\t\tu(N - 1, t + 1) = u(1, t + 1);\n\t}\n}\n\n/// Uses forward Euler and upwind finite differences to compute u from time 0 to time T\n///\n/// @param[out] u solution at all time steps up to time T, each column corresponding to a time step (including the initial condition as first column)\n/// @param[out] time the time levels\n/// @param[in] u0 the initial conditions, as column vector\n/// @param[in] dt the time step size\n/// @param[in] T the final time at which to compute the solution (which we assume to be a multiple of dt)\n/// @param[in] N the number of grid points, INCLUDING BOUNDARY POINTS\n/// @param[in] a the advection velocity\n///\n\nvoid UpwindFD(Eigen::MatrixXd &u, Vector &time, const Vector u0, double dt, double T, int N, const std::function &a) {\n\t//const unsigned int nsteps = round(T / dt);\n\t//const double dx = 1. / (N - 1);\n\t//u.resize(N, nsteps + 1);\n\t//time.resize(nsteps + 1);\n\n\t// (write your solution here)\n\tSimpleUpwindFD(u, time, u0, dt, T, N, a);\n}\n\n///\n/// Uses forward Euler and centered finite differences to compute u from time 0 to time T\n///\n/// @param[out] u solution at all time steps up to time T, each column corresponding to a time step (including the initial condition as first column)\n/// @param[out] time the time levels\n/// @param[in] u0 the initial conditions, as column vector\n/// @param[in] dt the time step size\n/// @param[in] T the final time at which to compute the solution (which we assume to be a multiple of dt)\n/// @param[in] N the number of grid points, INCLUDING BOUNDARY POINTS\n/// @param[in] a the advection velocity\n///\n\nvoid CenteredFD(Eigen::MatrixXd &u, Vector &time, const Vector u0, double dt, double T, int N, const std::function &a) {\n\tconst unsigned int nsteps = round(T / dt);\n\tconst double dx = 1. / (N - 1);\n\tu.resize(N, nsteps + 1);\n\ttime.resize(nsteps + 1);\n\n\t/* Initialize u */\n\tu.col(0) << u0;\n\ttime[0] = 0;\n\t// (write your solution here)\n\tfor (unsigned int t = 0; t < nsteps; ++t) {\n\t\tfor (int x = 1; x < N - 1; ++x) {\n\t\t\tu(x, t + 1) = u(x, t) / dt - a(x / dx) * (u(x + 1, t) - u(x - 1, t)) / (2 * dx);\n\t\t}\n\t\tu(0, t + 1) = u(N - 2, t + 1);\n\t\tu(N - 1, t + 1) = u(1, t + 1);\n\t}\n}\n\n/* Initial condition: rectangle */\ndouble U0(double x) {\n\tif (x < 0.25 || x > 0.75)\n\t\treturn 0;\n\telse\n\t\treturn 2.;\n}\n\nint main(int, char **) {\n\tdouble T = 2.;\n\tdouble dt = 0.002; // Change this for timestep comparison\n\tint N = 101;\n\n\tauto a = [](double x) {\n\t\treturn std::sin(2 * M_PI * x);\n\t};\n\n\tVector u0(N);\n\tdouble h = 1. / (N - 1);\n\t/* Initialize u0 */\n\tfor (int i = 0; i < u0.size(); i++)\n\t\tu0[i] = U0(h * (double) i);\n\n\tEigen::MatrixXd u_simpleupwind;\n\tVector time_simpleupwind;\n\tSimpleUpwindFD(u_simpleupwind, time_simpleupwind, u0, dt, T, N, a);\n\twriteToFile(\"time_simpleupwind.txt\", time_simpleupwind);\n\twriteMatrixToFile(\"u_simpleupwind.txt\", u_simpleupwind);\n\n\tEigen::MatrixXd u_upwind;\n\tVector time_upwind;\n\tUpwindFD(u_upwind, time_upwind, u0, dt, T, N, a);\n\twriteToFile(\"time_upwind.txt\", time_upwind);\n\twriteMatrixToFile(\"u_upwind.txt\", u_upwind);\n\n\tEigen::MatrixXd u_centered;\n\tVector time_centered;\n\tCenteredFD(u_centered, time_centered, u0, dt, T, N, a);\n\twriteToFile(\"time_centered.txt\", time_centered);\n\twriteMatrixToFile(\"u_centered.txt\", u_centered);\n}\n", "meta": {"hexsha": "5aab281dc4236cd5f35b91981681a54ecef5cd3f", "size": 4815, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series4/linear-transp-1d/linear_transport.cpp", "max_stars_repo_name": "westernmagic/NumPDE", "max_stars_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "series4/linear-transp-1d/linear_transport.cpp", "max_issues_repo_name": "westernmagic/NumPDE", "max_issues_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-04-01T22:52:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T16:21:55.000Z", "max_forks_repo_path": "series4/linear-transp-1d/linear_transport.cpp", "max_forks_repo_name": "westernmagic/NumPDE", "max_forks_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9328358209, "max_line_length": 149, "alphanum_fraction": 0.6398753894, "num_tokens": 1521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033682, "lm_q2_score": 0.8688267677469952, "lm_q1q2_score": 0.7579187383607082}} {"text": "//\n// main.cpp\n// Ransac\n//\n// Created by JiangZhigang on 2020/11/29.\n// Copyright © 2020 JiangZhigang. All rights reserved.\n//\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n\nstd::vector generate_data(float k, float b, int n, float line_noise_level = 10, float random_noise_count = 200, bool add_ellipse = false){\n std::default_random_engine e(static_cast(time(nullptr)));\n std::uniform_int_distribution<> u(-line_noise_level, line_noise_level);\n \n std::vector points;\n for(int i=-n; i 0){\n float y = sqrt(b_*b_ * q);\n float r = atan(k);\n float c = cos(r);\n float s = sin(r);\n\n auto p1 = cv::Point2f(i, y);\n p1 = cv::Point2f(p1.x * c + p1.y * (-s), p1.x * s + p1.y * c + b);\n points.push_back(p1);\n auto p2 = cv::Point2f(i, -y);\n p2 = cv::Point2f(p2.x * c + p2.y * (-s), p2.x * s + p2.y * c + b);\n points.push_back(p2);\n }\n }\n \n std::uniform_int_distribution<> u_(-n, n);\n for(int i=0; i& points){\n int h = board.cols, w = board.rows;\n for(auto const& point : points){\n cv::Point2f p = cv::Point2f(h/2+point.x, w/2-point.y);//origin change center\n cv::circle(board, p, 1, cv::Scalar(255, 255, 255), -1);\n }\n}\n\nvoid draw_line(cv::Mat& board, float k, float b, cv::Scalar color){\n int h = board.cols, w = board.rows;\n cv::Point2f p1 = cv::Point2f(-h, -w * k + b);\n p1 = cv::Point2f(h/2+p1.x, w/2-p1.y);\n cv::Point2f p2 = cv::Point2f(h, w * k + b);\n p2 = cv::Point2f(h/2+p2.x, w/2-p2.y);\n cv::line(board, p1, p2, color, 1);\n}\n\n\nfloat calc_error(const cv::Point2f& point, float k, float b){\n // distance of point to line\n float A = k, B = -1, C = b;\n return abs(A * point.x + B * point.y + C) / sqrt(A * A + B * B);\n}\n\nfloat calc_error_y2(const cv::Point2f& point, float k, float b){\n return pow(abs(b + point.x * k - point.y), 2);\n}\n\ndouble calc_loss(const std::vector& points, double w1, double w2){\n // MSE\n double sse = 0;\n for (auto const& point: points) {\n double se = calc_error_y2(point, w2, w1);\n sse += se;\n }\n double mes = sse / (2 * points.size());\n return mes;\n\n}\n\n/// use the Eigen libary to implement the least square method\n/// @param points a set of observed data points\n/// @param k_ k of model parameters which best fit the data\n/// @param b_ b of model parameters which best fit the data\n/// @return whether a good model has been found\nbool least_squares(const std::vector& points, float& k_, float& b_){\n Eigen::MatrixXd A(points.size(), 2);\n Eigen::VectorXd b(points.size());\n \n int i = 0;\n for(auto const& point : points){\n A.row(i) = Eigen::Vector2d(point.x, 1);\n b(i) = point.y;\n i++;\n }\n // Eigen provides multiple solver\n // Eigen::MatrixXd solution = A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);\n Eigen::VectorXd solution = A.colPivHouseholderQr().solve(b);\n\n if(solution.size() == 2){\n k_ = solution(0);\n b_ = solution(1);\n return true;\n }\n return false;\n}\n\n\n/// use the Eigen libary to implement the least square method\n/// @param points a set of observed data points\n/// @param k_ k of model parameters which best fit the data\n/// @param b_ b of model parameters which best fit the data\n/// @return whether a good model has been found\nbool least_squares_b(const std::vector& points, float& k_, float& b_){\n Eigen::MatrixXd A(points.size(), 2);\n Eigen::VectorXd b(points.size());\n \n int i = 0;\n for(auto const& point : points){\n A.row(i) = Eigen::Vector2d(point.x, 1);\n b(i) = point.y;\n i++;\n }\n \n Eigen::MatrixXd ATA = A.transpose() * A;\n auto rank = Eigen::FullPivLU(ATA).rank();\n if(rank < ATA.rows()){\n std::cout << \"rank of A^TA is \" << rank << \", can't directly get inverse\" << std::endl;\n return false;\n }\n \n Eigen::VectorXd solution = ATA.inverse() * A.transpose() * b;\n if(solution.size() == 2){\n k_ = solution(0);\n b_ = solution(1);\n return true;\n }\n return false;\n}\n\n\n/// implement the least square method from [there](https://blog.csdn.net/pl20140910/article/details/51926886)\n/// @param points a set of observed data points\n/// @param k_ k of model parameters which best fit the data\n/// @param b_ b of model parameters which best fit the data\n/// @return whether a good model has been found\nbool least_squares_a(const std::vector& points, float& k_, float& b_){\n int n = (int)points.size();\n float A=0,B=0,C=0,D=0;\n for(auto const& point : points){\n A += point.x * point.x;\n B += point.x;\n C += point.x * point.y;\n D += point.y;\n }\n \n float temp = (n*A - B*B);\n if(temp){\n k_ = (n*C - B*D) / temp;\n b_ = (A*D - B*C) / temp;\n return true;\n }else{\n return false;\n }\n}\n\n\n/// standard RANSAC algorithm from [wikipedia](https://en.wikipedia.org/wiki/Random_sample_consensus)\n/// @param data a set of observed data points\n/// @param k_ k of model parameters which best fit the data\n/// @param b_ b of model parameters which best fit the data\n/// @param n the minimum number of data values required to fit the model\n/// @param k the maximum number of iterations allowed in the algorithm\n/// @param t a threshold value for determining when a data point fits a model\n/// @param d the number of close data values required to assert that a model fits well to data\n/// @return whether a good model has been found\nbool ransac(const std::vector& data, float& k_, float& b_, int n = 10, int k = 1000, float t = 10, int d = 10){\n int c = (int)data.size();\n std::default_random_engine e(static_cast(time(nullptr)));\n std::uniform_int_distribution<> u(0, c-1);\n \n float best_error = FLT_MAX;\n float best_model_k = 0, best_model_b = 0;\n \n std::vector best_indexs;\n int it = 0;\n while (it++ < k) {\n // n randomly selected values from data\n int maybe_it = 0;\n std::vector visited(c, false);\n std::vector maybe_inliers;\n while(true && maybe_it++ < k ){\n int i = u(e);\n if(visited[i]) continue;\n \n maybe_inliers.push_back(data[i]);\n visited[i] = true;\n \n if(maybe_inliers.size() == n) break;\n }\n if(maybe_inliers.empty()) return false;\n \n // model parameters fitted to maybeinliers\n float maybe_model_k = 0, maybe_model_b = 0;\n least_squares(maybe_inliers, maybe_model_k, maybe_model_b);\n std::vector also_inliers;\n \n for(int i = 0; i < c; i++){\n if(visited[i]) continue;// every point in data not in maybeinliers\n float error = calc_error(data[i], maybe_model_k, maybe_model_b);\n if(error > t) continue;//point fits maybemodel with an error smaller than t\n also_inliers.push_back(data[i]);//add point to alsoinliers\n }\n// std::cout << also_inliers.size() << std::endl;\n if(also_inliers.size() <= d) continue;//the number of elements in alsoinliers is > d\n \n // this implies that we may have found a good model\n // now test how good it is\n \n // parameters fitted to all points in maybeinliers and alsoinliers\n also_inliers.insert(also_inliers.end(), maybe_inliers.begin(), maybe_inliers.end());\n float better_model_k = 0, better_model_b = 0;\n least_squares(also_inliers, better_model_k, better_model_b);\n \n // measure of how well model fits these points\n float this_error = 0;\n for(int i = 0; i < also_inliers.size(); i++){\n this_error += calc_error(also_inliers[i], better_model_k, better_model_b);\n }\n this_error = this_error/also_inliers.size();\n \n \n bool better = this_error < best_error;\n if(better){\n best_model_k = better_model_k;\n best_model_b = better_model_b;\n best_error = this_error;\n }\n }\n \n k_ = best_model_k;\n b_ = best_model_b;\n return best_error != FLT_MAX;\n}\n\n/// gradient descent\n/// @param data a set of observed data points\n/// @param k_ k of model parameters which best fit the data\n/// @param b_ b of model parameters which best fit the data\n/// @param alpha learing rate\n/// @param k the maximum number of iterations allowed in the algorithm\n/// @param min_loss the loss of close data values required to assert that a model fits well to data\nbool gradient_descent(const std::vector& data, float& k_, float& b_, double alpha = 0.1, int k = 1000, double min_loss = 0.001){\n int c = (int)data.size();\n double loss = FLT_MAX;\n double loss_pre = loss;\n \n int it = 0;\n double w1 = 0, w2 = 0;\n do {\n // the partial derivative of w1,w2\n double g1 = 0, g2 = 0;\n for(int i=0; i= min_loss && it++ < k);\n \n \n // std::cout<<\"gradient_descent loss it:\" << it << \" loss:\"<< loss << std::endl;\n k_ = w2;\n b_ = w1;\n return loss != FLT_MAX && !isinf(loss);\n}\n\nint main(int argc, const char * argv[]) {\n std::cout << std::fixed << std::setprecision(8);\n \n float k = 0.5;\n float b = 20;\n cv::Mat board = cv::Mat(800, 800, CV_8UC3);\n \n std::vector points = generate_data(k, b, 300, 10, 400, true);\n \n std::cout<< \"original k:\" << k << \" b:\" << b << std::endl;\n draw_data(board, points);\n draw_line(board, k, b, cv::Scalar(255,255,255));\n \n float k_, b_;\n// if(least_squares_a(points, k_, b_)){\n// std::cout<< \"least squares a:\" << k_ << \" b:\" << b_ << std::endl;\n// draw_line(board, k_, b_, cv::Scalar(0,255,0));\n// }\n//\n// if(least_squares_b(points, k_, b_)){\n// std::cout<< \"least squares b:\" << k_ << \" b:\" << b_ << std::endl;\n// draw_line(board, k_, b_, cv::Scalar(0,255,0));\n// }\n\n if(least_squares(points, k_, b_)){\n std::cout<< \"least squares:\" << k_ << \" b:\" << b_ << std::endl;\n draw_line(board, k_, b_, cv::Scalar(0,255,0));\n }\n\n\n if(ransac(points, k_, b_, 10, 1000, 50, 100)){\n std::cout<< \"ransac k:\" << k_ << \"b:\" << b_ << std::endl;\n draw_line(board, k_, b_, cv::Scalar(0,0,255));\n }\n\n if(gradient_descent(points, k_, b_, 0.00004, 1e8, 1e-8)){\n std::cout<< \"gradient_descent k:\" << k_ << \"b:\" << b_ << std::endl;\n draw_line(board, k_, b_, cv::Scalar(0,255,255));\n }\n\n cv::imshow(\"board\", board);\n cv::waitKey();\n return 0;\n}\n", "meta": {"hexsha": "e9ac4671c8be57dc3d82ad04d7d35bc8ad937d73", "size": 11707, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fit_line.cpp", "max_stars_repo_name": "zhigangjiang/CV-Experiment", "max_stars_repo_head_hexsha": "9846dd3700dbb575ceaf23af7357d54af5be366e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-12-08T02:22:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T10:05:04.000Z", "max_issues_repo_path": "fit_line.cpp", "max_issues_repo_name": "zhigangjiang/CV-Experiment", "max_issues_repo_head_hexsha": "9846dd3700dbb575ceaf23af7357d54af5be366e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fit_line.cpp", "max_forks_repo_name": "zhigangjiang/CV-Experiment", "max_forks_repo_head_hexsha": "9846dd3700dbb575ceaf23af7357d54af5be366e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3313782991, "max_line_length": 151, "alphanum_fraction": 0.5811907406, "num_tokens": 3412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.757697723706605}} {"text": "/*\n * =====================================================================================\n *\n * Filename: 1.cpp\n *\n * Description: Demo Program for Eigen C++\n * Library.\n *\n * Version: 1.0\n * Created: 08/28/2021 03:09:00 PM\n * Revision: none\n * Compiler: gcc\n *\n * Author: Dhruva Gole (181030017), goledhruva@gmail.com\n * Organization: VJTI\n *\n * =====================================================================================\n */\n\n#include \n#include \n\nint main()\n{\n\tEigen::MatrixXd m(3,3);\n\tEigen::Matrix3d a;\n\ta << 24, -4, -4,\n\t \t -4, 24, -4,\n\t\t -4, -4, 4;\n m << a.inverse();\n std::cout << \"Matrix a = \\n\" << a << std::endl;\n std::cout << \"Addition of two matrices: a + (inverse a)\\n\" << a+m << std::endl;\n std::cout << \"And product is:\\n\" << a*m << std::endl;\n std::cout << \"The Determinant of a is:\\n\" << a.determinant() << std::endl;\n return 0;\n}\n\n", "meta": {"hexsha": "1973a99ca42148854faf9bc1ee4dd2709f1e7432", "size": 943, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extras/srcEigencpp/1.cpp", "max_stars_repo_name": "DhruvaG2000/dhruvag2000.github.io", "max_stars_repo_head_hexsha": "ce14e7c61db0ccf141209d888326b365f942e34d", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "extras/srcEigencpp/1.cpp", "max_issues_repo_name": "DhruvaG2000/dhruvag2000.github.io", "max_issues_repo_head_hexsha": "ce14e7c61db0ccf141209d888326b365f942e34d", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extras/srcEigencpp/1.cpp", "max_forks_repo_name": "DhruvaG2000/dhruvag2000.github.io", "max_forks_repo_head_hexsha": "ce14e7c61db0ccf141209d888326b365f942e34d", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8157894737, "max_line_length": 88, "alphanum_fraction": 0.4305408271, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475683211323, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7576720455103295}} {"text": "#include\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nint main(int argc, char const *argv[])\n{\n /* code */\n\n Eigen:: MatrixXf m = Eigen::MatrixXf::Random(3,7);\nstd::cout << \"Here is the matrix m:\" << std::endl << m << std::endl;\n Eigen::JacobiSVD< Eigen:: MatrixXf> svd(m,Eigen::ComputeThinU | Eigen::ComputeThinV);\ncout << \"Its singular values are:\" << endl << svd.singularValues() << endl;\ncout << \"Its left singular vectors are the columns of the thin U matrix:\" << endl << svd.matrixU() << endl;\ncout << \"Its right singular vectors are the columns of the thin V matrix:\" << endl << svd.matrixV() << endl;\n Eigen::Vector3f rhs(1, 0, 0);\ncout << \"Now consider this rhs vector:\" << endl << rhs << endl;\ncout << \"A least-squares solution of m*x = rhs is:\" << endl << svd.solve(rhs) << endl;\n return 0;\n}\n", "meta": {"hexsha": "d80d265de4d20231376c3982c3e8bd4b407f17a3", "size": 885, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/svd_test.cpp", "max_stars_repo_name": "Colaplusice/libfranka", "max_stars_repo_head_hexsha": "a330115280de29de5d8cf2dbe311047c073711d5", "max_stars_repo_licenses": ["Apache-2.0"], "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/svd_test.cpp", "max_issues_repo_name": "Colaplusice/libfranka", "max_issues_repo_head_hexsha": "a330115280de29de5d8cf2dbe311047c073711d5", "max_issues_repo_licenses": ["Apache-2.0"], "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/svd_test.cpp", "max_forks_repo_name": "Colaplusice/libfranka", "max_forks_repo_head_hexsha": "a330115280de29de5d8cf2dbe311047c073711d5", "max_forks_repo_licenses": ["Apache-2.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.875, "max_line_length": 108, "alphanum_fraction": 0.6451977401, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191246389617, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7576692900387526}} {"text": "#include \n#include \n#include \n\ntemplate\nusing Vec = Eigen::Matrix;\n\n// https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula\ntemplate \nvoid rotate_rodrigues(const Vec& k, const T& theta, const Vec& v, Vec& v_rot)\n{\n v_rot = v*cos(theta) + k.cross(v)*sin(theta) + k*k.dot(v)*(1-cos(theta));\n}\n\nusing namespace codegenvar; \n\nbool equals(const Vec3& a, const Vec3& b)\n{\n for(int i = 0; i<3; i++)\n if (!a(i).equals(b(i)))\n return false;\n return true;\n}\n\n// main:\nint main()\n{\n Symbol angle(\"theta\");\n Vec3 axis = namedVector<3>(\"k\"), point = namedVector<3>(\"v\");\n \n Vec3 r1;\n\n // Use Rodrigues' rotation formula to calculate the rotation of the point:\n rotate_rodrigues(axis, angle, point, r1);\n std::cout << \"Rodrigues:\\n\" << r1 << std::endl;\n\n // Use Eigen to calculate the rotation of the point:\n Vec3 r = Eigen::AngleAxis(angle, axis)*point;\n std::cout << \"\\nEigen:\\n\" << r << std::endl;\n \n // Check for mathematical equality:\n std::cout << \"\\nThe two expressions are \" \n << (equals(r1, r) ? \"equal\" : \"not equal\") \n << \".\" << std::endl;\n\n // If we convert all expressions to their expanded form, we can see that they are identical.\n std::cout << \"\\nExpanded:\\n\";\n\n std::cout << \"\\nRodrigues:\\n\" << expanded(r1) << std::endl;\n std::cout << \"\\nEigen:\\n\" << expanded(r) << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "db8147c5a8b64f58c498653738f47eac1478c662", "size": 1515, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/rodrigues.cpp", "max_stars_repo_name": "bjornpiltz/CppCodeGenVar", "max_stars_repo_head_hexsha": "4f4707c88202695300e55db8909af29107bdc157", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-01-23T09:41:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T05:44:14.000Z", "max_issues_repo_path": "examples/rodrigues.cpp", "max_issues_repo_name": "bjornpiltz/CppCodeGenVar", "max_issues_repo_head_hexsha": "4f4707c88202695300e55db8909af29107bdc157", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2018-01-18T13:16:20.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-25T21:42:34.000Z", "max_forks_repo_path": "examples/rodrigues.cpp", "max_forks_repo_name": "bjornpiltz/CppCodeGenVar", "max_forks_repo_head_hexsha": "4f4707c88202695300e55db8909af29107bdc157", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0555555556, "max_line_length": 96, "alphanum_fraction": 0.596039604, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7573819304940953}} {"text": "#ifndef CANNON_MATH_INTERP_H\n#define CANNON_MATH_INTERP_H \n\n/*!\n * \\file cannon/math/interp.hpp\n * \\brief File containing utilities for doing function interpolation.\n */\n\n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace Eigen;\n\nnamespace cannon {\n namespace math {\n\n /*!\n * \\brief Class representing the cubic spline interpolation of a set of\n * points. Following https://timodenk.com/blog/cubic-spline-interpolation/.\n */\n class CubicSpline {\n public:\n\n enum class BoundaryType {\n FirstDeriv,\n SecondDeriv,\n NotAKnot\n };\n\n CubicSpline() = delete;\n\n /*!\n * \\brief Constructor taking data to interpolate, boundary type for the\n * spline, and values of boundary conditions. Data should be sorted in\n * increasing order of xs.\n */\n CubicSpline(const std::vector& xs, const std::vector& ys,\n BoundaryType bd = BoundaryType::SecondDeriv,\n double bd_first = 0.0, double bd_last = 0.0);\n /*!\n * \\brief Constructor taking data to interpolate, boundary type for the\n * spline, and values of boundary conditions. Data should be sorted in\n * increasing order of xs.\n */\n CubicSpline(const std::vector& pts,\n BoundaryType bd = BoundaryType::SecondDeriv,\n double bd_first = 0.0, double bd_last = 0.0);\n\n /*!\n * \\brief Functional operator. \n */\n double operator()(double x) const;\n\n /*!\n * \\brief Get the derivative of this spline of input order at the input\n * point.\n *\n * \\param x The point to evaluate curve derivative at.\n * \\param order Derivative order to evaluate.\n *\n * \\returns The derivative.\n */\n double deriv(double x, unsigned int order = 1) const;\n\n /*!\n * \\brief Get the number of polynomials defining this spline.\n *\n * \\returns Number of polynomials.\n */\n inline unsigned int num_polys() const;\n\n private:\n /*!\n * \\brief Compute coefficients for spline from data points and boundary\n * conditions.\n */\n void compute_coeffs_();\n\n /*!\n * \\brief Compute A matrix for system of equations defining cubic\n * spline.\n *\n * \\returns A matrix which will be solved to compute spline\n * coefficients.\n */\n SparseMatrix construct_A_mat_() const;\n\n /*!\n * \\brief Compute b vector for system of equations defining cubic\n * spline.\n *\n * \\returns b vector which will be used to solve system of equations\n * for spline coefficients.\n */\n VectorXd construct_b_vec_() const;\n\n /*!\n * \\brief Find the closest idx such that xs_[idx] <= x\n *\n * \\param x Input value to locate\n *\n * \\returns Index of closest x datum\n */\n unsigned int find_closest_x_(double x) const;\n\n std::vector xs_; //!< X-values of data\n std::vector ys_; //!< Y-values of data\n\n const BoundaryType bd_; //!< Type of boundary condition for this spline\n const double bd_first_; //!< First boundary condition value\n const double bd_last_; //!< Last boundary condition value\n\n std::vector a_coeffs_; //!< Coefficients of x^3 for each polynomial\n std::vector b_coeffs_; //!< Coefficients of x^2 for each polynomial\n std::vector c_coeffs_; //!< Coefficients of x for each polynomial\n std::vector d_coeffs_; //!< Constant coefficients for each polynomial\n\n };\n\n /*!\n * \\brief Class representing a multivariate spline, defined by its\n * component coordinate splines.\n */\n class MultiSpline {\n public:\n\n MultiSpline() = delete;\n\n /*!\n * \\brief Constructor taking trajectory times and coordinate points, as\n * well as boundary conditions that will be set uniformly for each\n * spline.\n */\n MultiSpline(\n const std::vector ×, const std::vector &coords,\n CubicSpline::BoundaryType bd = CubicSpline::BoundaryType::SecondDeriv,\n double bd_first = 0.0, double bd_last = 0.0);\n\n /*!\n * \\brief Functor operator taking a time and returning the coordinates\n * of the multispline at that time.\n *\n * \\param t Time to evaluate spline at.\n *\n * \\returns Value of spline at that time.\n */\n VectorXd operator()(double t) const;\n\n /*!\n * \\brief Compute derivative with respect to time parameterization of\n * this cubic spline.\n *\n * \\param t The time to get derivative at.\n * \\param order The order of derivative to compute.\n *\n * \\returns The derivative.\n */\n VectorXd deriv(double t, unsigned int order = 1) const;\n\n /*!\n * \\brief Compute a normal vector for this spline at the input time.\n *\n * \\param t The time to compute a normal for.\n *\n * \\returns The computed normal. \n */\n VectorXd normal(double t) const;\n\n\n private:\n std::vector> coord_splines_; //!< Coordinate spline functions\n unsigned int dim_; //!< Dimension of spline\n };\n\n /*!\n * \\brief Compute the Chebyshev points between the input bounds. See\n * https://en.wikipedia.org/wiki/Chebyshev_nodes \n *\n * \\param num Number of points to generate\n * \\param low Lower limit for points\n * \\param high Upper limit for points\n *\n * \\returns A vector containing the Chebyshev points.\n */\n std::vector cheb_points(unsigned int num, double low=-1.0, double high=1.0);\n\n /*!\n * \\brief Compute the Lagrange interpolant for the input function on the\n * input points.\n *\n * \\param f The function to interpolate.\n * \\param pts The points to interpolate on.\n *\n * \\returns The Lagrange interpolating polynomial on the input points.\n */\n std::function\n lagrange_interp(std::function f, const std::vector& pts);\n\n /*!\n * \\brief Interpolate between the two input vectors.\n *\n * \\param a First vector\n * \\param b Second vector\n * \\param t Interpolation amount. Should be between 0 and 1\n *\n * \\returns Interpolated vector.\n */\n VectorXd lerp(const Ref &a, const Ref &b,\n double t);\n\n /*!\n * \\brief Compute the projection of the first vector onto the second.\n *\n * \\param a The vector to be projected\n * \\param b The vector that projection is computed with respect to.\n *\n * \\returns The projected vector.\n */\n VectorXd projection(const Ref &a,\n const Ref &b);\n\n /*!\n * \\brief Compute the complementary projection of the first vector with\n * respect to the second.\n *\n * \\param a The vector to be projected\n * \\param b The vector that projection is computed with respect to.\n *\n * \\returns The complementary projection.\n */\n VectorXd complementary_projection(const Ref &a,\n const Ref &b);\n }\n} \n\n#endif /* ifndef CANNON_MATH_INTERP_H */\n", "meta": {"hexsha": "e27f164ada6b9fcfee80940282dfe9b3a99b5d7c", "size": 7665, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/math/interp.hpp", "max_stars_repo_name": "cannontwo/cannon", "max_stars_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cannon/math/interp.hpp", "max_issues_repo_name": "cannontwo/cannon", "max_issues_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-01-12T23:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T17:29:01.000Z", "max_forks_repo_path": "cannon/math/interp.hpp", "max_forks_repo_name": "cannontwo/cannon", "max_forks_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8049792531, "max_line_length": 98, "alphanum_fraction": 0.5958251794, "num_tokens": 1672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7573819207338431}} {"text": "// Boost.Geometry\n// QuickBook Example\n\n// Copyright (c) 2018, Oracle and/or its affiliates\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[densify_strategy\n//` Shows how to densify a linestring in geographic coordinate system\n\n#include \n\n#include \n#include \n#include \n\nint main()\n{\n namespace bg = boost::geometry;\n typedef bg::model::point > point_type;\n typedef bg::model::linestring linestring_type;\n\n linestring_type ls;\n bg::read_wkt(\"LINESTRING(0 0,1 1)\", ls);\n\n linestring_type res;\n\n bg::srs::spheroid spheroid(6378137.0, 6356752.3142451793);\n bg::strategy::densify::geographic<> strategy(spheroid);\n\n boost::geometry::densify(ls, res, 50000.0, strategy);\n\n std::cout << \"densified: \" << boost::geometry::wkt(res) << std::endl;\n\n return 0;\n}\n\n//]\n\n//[densify_strategy_output\n/*`\nOutput:\n[pre\ndensified: LINESTRING(0 0,0.249972 0.250011,0.499954 0.500017,0.749954 0.750013,1 1)\n]\n*/\n//]\n", "meta": {"hexsha": "eb9934995c77efb1447f1996590476e9fd5f2bc1", "size": 1314, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/src/examples/algorithms/densify_strategy.cpp", "max_stars_repo_name": "jonasdmentia/geometry", "max_stars_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1155.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:30:30.000Z", "max_issues_repo_path": "doc/src/examples/algorithms/densify_strategy.cpp", "max_issues_repo_name": "jonasdmentia/geometry", "max_issues_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "doc/src/examples/algorithms/densify_strategy.cpp", "max_forks_repo_name": "jonasdmentia/geometry", "max_forks_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 228.0, "max_forks_repo_forks_event_min_datetime": "2015-01-13T12:55:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:11:05.000Z", "avg_line_length": 25.7647058824, "max_line_length": 84, "alphanum_fraction": 0.7123287671, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.757320689245425}} {"text": "#include \"ReferenceModel.hpp\"\n#include \n#include \n#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\nReferenceModel::ReferenceModel(void)\n{\n this->dt = 0.0;\n this->nStates = 0;\n this->nInputs = 0;\n this->nOutputs = 0;\n}\nReferenceModel::~ReferenceModel(void)\n{\n \n}\n\nvoid ReferenceModel::initialize(const ReferenceModel_Config_t _config)\n{\n // Safety checks\n if (_config.A.cols() != _config.A.rows())\n throw invalid_argument(\"A is not a squre matrix!\");\n if (_config.A.rows() != _config.B.rows())\n throw invalid_argument(\"A and B have different # of rows!\");\n \n this->dt = _config.dt;\n this->Aref = _config.A;\n this->Bref = _config.B;\n this->nStates = this->Aref.cols();\n this->nInputs = this->Bref.cols();\n this->nOutputs = this->nStates; // full states output\n this->Cref = MatrixXd::Identity(this->nOutputs, this->nOutputs);\n \n // Safety checks\n if(_config.states0.size() != this->nStates)\n throw invalid_argument(\"Unexpected initial states size!\");\n\n this->states0 = VectorXd::Zero(this->nStates); \n for(int i=0; i<(this->nStates); i++) {\n //ROS_INFO(\"initialize: %.4f\\n\", _config.states0(i));\n this->states0(i) = _config.states0(i);\n }\n reset();\n}\n\nvoid ReferenceModel::reset()\n{\n this->states = VectorXd::Zero(this->nStates);\n for(int i=0; i<(this->nStates); i++) {\n\n this->states(i) = this->states0(i);\n //ROS_INFO(\"Reset: %.4f, \", this->states(i));\n }\n //ROS_INFO(\"\\n\");\n}\n\nvoid ReferenceModel::update(const VectorXd _inputs)\n{\n // Safety check\n if(_inputs.size() != this->nInputs)\n throw invalid_argument(\"Unexpected inputs size!\");\n //ROS_INFO(\"update: %.4f\", _inputs(0));\n\n // Euler integration\n VectorXd states_dot = this->Aref * this->states + this->Bref * _inputs;\n this->states += states_dot * this->dt;\n}\n\nvoid ReferenceModel::get_outputs(VectorXd &_outputs)\n{\n _outputs = this->Cref * this->states;\n}\n\nvoid ReferenceModel::get_states(VectorXd &_states)\n{\n _states = VectorXd::Zero(this->nStates);\n for (int i=0; i<(this->nStates); i++) {\n _states(i) = this->states(i);\n }\n //ROS_INFO(\"get_states A: %.4f, %.4f\", _states(0), _states(1));\n //ROS_INFO(\"get_states B: %.4f, %.4f\", this->states(0), this->states(1));\n}\n", "meta": {"hexsha": "8a19d503f3c3bb296c180931a5cb614b07bab13d", "size": 2373, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "crazyflie_mrac_controllers/src/ReferenceModel.cpp", "max_stars_repo_name": "fjctp/crazyflie_mrac_ros", "max_stars_repo_head_hexsha": "d43df1832860addd0ff7fbad391c7871cb3c6577", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-09T03:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T06:00:12.000Z", "max_issues_repo_path": "crazyflie_mrac_controllers/src/ReferenceModel.cpp", "max_issues_repo_name": "fjctp/crazyflie_mrac_ros", "max_issues_repo_head_hexsha": "d43df1832860addd0ff7fbad391c7871cb3c6577", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "crazyflie_mrac_controllers/src/ReferenceModel.cpp", "max_forks_repo_name": "fjctp/crazyflie_mrac_ros", "max_forks_repo_head_hexsha": "d43df1832860addd0ff7fbad391c7871cb3c6577", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-24T22:48:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-24T22:48:29.000Z", "avg_line_length": 27.275862069, "max_line_length": 77, "alphanum_fraction": 0.6232616941, "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998822, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7573206736045853}} {"text": "/**\n * @author Eric Cousineau , member of Dr. Aaron\n * Ames's AMBER Lab\n */\n#ifndef EIGEN_UTILITIES_INTERP_UTILITIES_H\n #define EIGEN_UTILITIES_INTERP_UTILITIES_H\n\n#include \n\n#include \n#include \n\nnamespace eigen_utilities\n{\n\ntemplate\nT find_lower_index(const Container &data, const T &value, bool do_saturate = false)\n{\n // Assume sorted\n if (data.size() == 0)\n return -1;\n else\n {\n int index = 0;\n int last = data.size() - 1;\n if (do_saturate)\n {\n const T &min = data[0];\n const T &max = data[last];\n if (value < min)\n return -2;\n if (value > max)\n return -3; // Return this as upper\n }\n while (index + 1 < data.size())\n {\n const T &lower = data[index];\n const T &upper = data[index + 1];\n if (value >= lower && value <= upper)\n return index;\n else\n index += 1;\n }\n return -1;\n }\n}\n\ntemplate\nclass BilinearInterp\n{\npublic:\n Eigen::VectorXd xs;\n Eigen::VectorXd ys;\n std::vector > zs;\nprivate:\n ZType q11;\n ZType q21;\n ZType q12;\n ZType q22;\n ZType r1;\n ZType r2;\n ZType z;\npublic:\n void check()\n {\n common_assert(xs.size() > 0);\n common_assert(ys.size() > 0);\n common_assert_msg(zs.size() == xs.size(), \"Bad tensor x-size: \" << zs.size() << \" != \" << xs.size());\n for (int i = 0; i < zs.size(); ++i)\n common_assert_msg(zs[i].size() == ys.size(), \"Bad tensor y-size at [\" << i << \"]: \" << zs[i].size() << \" != \" << ys.size());\n }\n\n inline const ZType& eval(const Eigen::VectorXd &v, bool do_saturate = false)\n {\n assert_size_vector(v, 2);\n return eval(v(0), v(1), do_saturate);\n }\n\n inline const ZType& eval(double x, double y, bool do_saturate = false)\n {\n// common_assert(xs.size() > 0);\n// common_assert(ys.size() > 0);\n// assert_size_matrix(zs, xs.size(), ys.size());\n // http://en.wikipedia.org/wiki/Bilinear_interpolation\n if (do_saturate)\n {\n double xmin = xs(0);\n double xmax = xs(xs.size() - 1);\n x = std::min(std::max(x, xmin), xmax);\n double ymin = ys(0);\n double ymax = ys(ys.size() - 1);\n y = std::min(std::max(y, ymin), ymax);\n }\n int x_index = find_lower_index(xs, x);\n int y_index = find_lower_index(ys, y);\n if (x_index == -1 || y_index == -1)\n throw std::runtime_error(\"Bilinear interpolation values out of range\");\n double xl = xs(x_index);\n double xu = xs(x_index + 1);\n double yl = ys(y_index);\n double yu = ys(y_index + 1);\n q11 = zs[x_index][y_index];\n q21 = zs[x_index + 1][y_index];\n q12 = zs[x_index][y_index + 1];\n q22 = zs[x_index + 1][y_index + 1];\n r1 = (xu - x) / (xu - xl) * q11 + (x - xl) / (xu - xl) * q21;\n r2 = (xu - x) / (xu - xl) * q12 + (x - xl) / (xu - xl) * q22;\n z = (yu - y) / (yu - yl) * r1 + (y - yl) / (yu - yl) * r2;\n return z;\n }\n};\n\n//class MatrixBilinearInterp\n//{\n//public:\n// Eigen::VectorXd xs;\n// Eigen::VectorXd ys;\n// std::vector > zs;\n//private:\n// Eigen::MatrixXd Z;\n// std::vector > interps;\n//public:\n// void checkAndInit()\n// {\n// common_assert(xs.size() > 0);\n// common_assert(ys.size() > 0);\n// common_assert_msg(zs.size() == xs.size(), \"Bad tensor x-size: \" << zs.size() << \" != \" << xs.size());\n// int rows = -1;\n// int cols = -1;\n// for (int i = 0; i < zs.size(); ++i)\n// {\n// common_assert_msg(zs[i].size() == ys.size(), \"Bad tensor y-size at [\" << i << \"]: \" << zs[i].size() << \" != \" << ys.size());\n// for (int j = 0; j < zs[i].size(); ++j)\n// {\n// if (rows == -1 && cols == -1)\n// assert_size_matrix(zs[i][j], rows, cols);\n// else\n// {\n// rows = zs[i][j].rows();\n// cols = zs[i][j].cols();\n// Z.resize(rows, cols);\n// }\n// }\n// }\n// std::vector > interp_row;\n// Eigen::MatrixXd blank(xs.size(), ys.size());\n// interp_row.assign(cols, BilinearInterp(xs, ys, blank));\n// interps.assign(rows, interp_row);\n// for (int ix = 0; ix < xs.size(); ++ix)\n// {\n// for (int iy = 0; iy < ys.size(); ++iy)\n// {\n// for (int ir = 0; ir < rows; ++ ir)\n// {\n// for (int ij = 0; ij < cols; ++ ij)\n// {\n// interps[ir][ij].zs(ix, iy) = zs[ix][iy](ir, ij);\n// }\n// }\n// }\n// }\n// }\n//};\n\n}\n\n#endif // EIGEN_UTILITIES_INTERP_UTILITIES_H\n", "meta": {"hexsha": "d7dd127619622ad06f91fb3c279239dce9d1346f", "size": 5157, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "eigen_utilities/include/eigen_utilities/interp_utilities.hpp", "max_stars_repo_name": "noelc-s/amber_developer_stack", "max_stars_repo_head_hexsha": "dda28b1b79f8df6eb56c41a0e1b5c1d167631176", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-18T04:36:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T04:36:22.000Z", "max_issues_repo_path": "eigen_utilities/include/eigen_utilities/interp_utilities.hpp", "max_issues_repo_name": "noelc-s/amber_developer_stack", "max_issues_repo_head_hexsha": "dda28b1b79f8df6eb56c41a0e1b5c1d167631176", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eigen_utilities/include/eigen_utilities/interp_utilities.hpp", "max_forks_repo_name": "noelc-s/amber_developer_stack", "max_forks_repo_head_hexsha": "dda28b1b79f8df6eb56c41a0e1b5c1d167631176", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-04T21:22:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T21:22:48.000Z", "avg_line_length": 30.6964285714, "max_line_length": 138, "alphanum_fraction": 0.4731433004, "num_tokens": 1468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7569395754721854}} {"text": "#include \n#include \n#include \n#include \n#include \n\nusing std::cout;\nusing std::endl;\nusing std::ofstream;\n \nusing std::default_random_engine;\nusing std::normal_distribution;\nusing std::bind;\n \n// start random number engine with fixed seed\ndefault_random_engine re{12345};\n\nnormal_distribution norm(5,2); // mean and standard deviation\nauto rnorm = bind(norm, re); \n \nint main() \n{\n using namespace Eigen;\n\n VectorXd x1(6);\n x1 << 1, 2, 3, 4, 5, 6;\n VectorXd x2 = VectorXd::LinSpaced(6, 1, 2);\n VectorXd x3 = VectorXd::Zero(6);\n VectorXd x4 = VectorXd::Ones(6);\n VectorXd x5 = VectorXd::Constant(6, 3);\n VectorXd x6 = VectorXd::Random(6);\n \n double data[] = {6,5,4,3,2,1};\n Map x7(data, 6);\n\n VectorXd x8 = x6 + x7;\n \n MatrixXd A1(3,3);\n A1 << 1 ,2, 3,\n 4, 5, 6,\n 7, 8, 9;\n MatrixXd A2 = MatrixXd::Constant(3, 4, 1);\n MatrixXd A3 = MatrixXd::Identity(3, 3);\n \n Map A4(data, 3, 2);\n \n MatrixXd A5 = A4.transpose() * A4;\n MatrixXd A6 = x7 * x7.transpose();\n MatrixXd A7 = A4.array() * A4.array();\n MatrixXd A8 = A7.array().log();\n MatrixXd A9 = A8.unaryExpr([](double x) { return exp(x); });\n MatrixXd A10 = MatrixXd::Zero(3,4).unaryExpr([](double x) { return rnorm(); });\n\n VectorXd x9 = A1.colwise().norm();\n VectorXd x10 = A1.rowwise().sum();\n \n MatrixXd A11(x1.size(), 3);\n A11 << x1, x2, x3;\n \n MatrixXd A12(3, x1.size());\n A12 << x1.transpose(),\n x2.transpose(),\n x3.transpose();\n \n JacobiSVD svd(A10, ComputeThinU | ComputeThinV);\n \n \n cout << \"x1: comman initializer\\n\" << x1.transpose() << \"\\n\\n\";\n cout << \"x2: linspace\\n\" << x2.transpose() << \"\\n\\n\";\n cout << \"x3: zeors\\n\" << x3.transpose() << \"\\n\\n\";\n cout << \"x4: ones\\n\" << x4.transpose() << \"\\n\\n\";\n cout << \"x5: constant\\n\" << x5.transpose() << \"\\n\\n\";\n cout << \"x6: rand\\n\" << x6.transpose() << \"\\n\\n\";\n cout << \"x7: mapping\\n\" << x7.transpose() << \"\\n\\n\";\n cout << \"x8: element-wise addition\\n\" << x8.transpose() << \"\\n\\n\";\n \n cout << \"max of A1\\n\";\n cout << A1.maxCoeff() << \"\\n\\n\";\n cout << \"x9: norm of columns of A1\\n\" << x9.transpose() << \"\\n\\n\";\n cout << \"x10: sum of rows of A1\\n\" << x10.transpose() << \"\\n\\n\"; \n \n cout << \"head\\n\";\n cout << x1.head(3).transpose() << \"\\n\\n\";\n cout << \"tail\\n\";\n cout << x1.tail(3).transpose() << \"\\n\\n\";\n cout << \"slice\\n\";\n cout << x1.segment(2, 3).transpose() << \"\\n\\n\";\n \n cout << \"Reverse\\n\";\n cout << x1.reverse().transpose() << \"\\n\\n\";\n \n cout << \"Indexing vector\\n\";\n cout << x1(0);\n cout << \"\\n\\n\";\n \n cout << \"A1: comma initilizer\\n\";\n cout << A1 << \"\\n\\n\";\n cout << \"A2: constant\\n\";\n cout << A2 << \"\\n\\n\";\n cout << \"A3: eye\\n\";\n cout << A3 << \"\\n\\n\";\n cout << \"A4: mapping\\n\";\n cout << A4 << \"\\n\\n\";\n cout << \"A5: matrix multiplication\\n\";\n cout << A5 << \"\\n\\n\";\n cout << \"A6: outer product\\n\";\n cout << A6 << \"\\n\\n\"; \n cout << \"A7: element-wise multiplication\\n\";\n cout << A7 << \"\\n\\n\"; \n cout << \"A8: ufunc log\\n\";\n cout << A8 << \"\\n\\n\"; \n cout << \"A9: custom ufucn\\n\";\n cout << A9 << \"\\n\\n\"; \n cout << \"A10: custom ufunc for normal deviates\\n\";\n cout << A10 << \"\\n\\n\"; \n cout << \"A11: np.c_\\n\";\n cout << A11 << \"\\n\\n\"; \n cout << \"A12: np.r_\\n\";\n cout << A12 << \"\\n\\n\"; \n \n cout << \"2x2 block startign at (0,1)\\n\";\n cout << A1.block(0,1,2,2) << \"\\n\\n\";\n cout << \"top 2 rows of A1\\n\";\n cout << A1.topRows(2) << \"\\n\\n\";\n cout << \"bottom 2 rows of A1\";\n cout << A1.bottomRows(2) << \"\\n\\n\";\n cout << \"leftmost 2 cols of A1\";\n cout << A1.leftCols(2) << \"\\n\\n\";\n cout << \"rightmost 2 cols of A1\";\n cout << A1.rightCols(2) << \"\\n\\n\";\n\n cout << \"Diagonal elements of A1\\n\";\n cout << A1.diagonal() << \"\\n\\n\";\n A1.diagonal() = A1.diagonal().array().square();\n cout << \"Transforming diagonal eelemtns of A1\\n\";\n cout << A1 << \"\\n\\n\";\n \n cout << \"Indexing matrix\\n\";\n cout << A1(0,0) << \"\\n\\n\";\n \n cout << \"singular values\\n\";\n cout << svd.singularValues() << \"\\n\\n\";\n \n cout << \"U\\n\";\n cout << svd.matrixU() << \"\\n\\n\";\n \n cout << \"V\\n\";\n cout << svd.matrixV() << \"\\n\\n\";\n}\n", "meta": {"hexsha": "babfbbd86e70fc4cc55b049e2c7a09055a78367b", "size": 4422, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "notebooks/test_eigen.cpp", "max_stars_repo_name": "itachi4869/sta-663-2021", "max_stars_repo_head_hexsha": "6f7a50f4a95207a26b01afa4439d992d767a1387", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/test_eigen.cpp", "max_issues_repo_name": "itachi4869/sta-663-2021", "max_issues_repo_head_hexsha": "6f7a50f4a95207a26b01afa4439d992d767a1387", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/test_eigen.cpp", "max_forks_repo_name": "itachi4869/sta-663-2021", "max_forks_repo_head_hexsha": "6f7a50f4a95207a26b01afa4439d992d767a1387", "max_forks_repo_licenses": ["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.48, "max_line_length": 83, "alphanum_fraction": 0.5085933967, "num_tokens": 1504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979618, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7568690245415026}} {"text": "/*************************************** \n* \n* LanXin TECH, All Rights Reserverd. \n* Created at Thu May 16 10:27:58 2019\n* Contributor: Ling Shi, Ph.D \n* Email: lshi@robvision.cn \n* \n***************************************/ \n\n#include \"common.h\"\n\n#include \n#include \n#include \n\nusing namespace std;\n\nnamespace lanXin {\n\n\nRotMat skew(Geo3d v) \n{\n\tRotMat rot;\n\trot.setZero();\n\n\trot(0, 1) = -v(2);\n\trot(0, 2) = v(1);\n\trot(1, 2) = -v(0);\n\n\trot(1, 0) = -rot(0, 1);\n\trot(2, 0) = -rot(0, 2);\n\trot(2, 1) = -rot(1, 2);\n\n\treturn rot;\n}\n\nGeo3d rodrigues2(const RotMat& matrix)\n{\n\tEigen::JacobiSVD svd(matrix, Eigen::ComputeFullV | Eigen::ComputeFullU);\n\tRotMat R = svd.matrixU() * svd.matrixV().transpose();\n\n\tdouble rx = R(2, 1) - R(1, 2);\n\tdouble ry = R(0, 2) - R(2, 0);\n\tdouble rz = R(1, 0) - R(0, 1);\n\n\tdouble s = sqrt((rx*rx + ry*ry + rz*rz)*0.25);\n\tdouble c = (R.trace() - 1) * 0.5;\n\tc = c > 1. ? 1. : c < -1. ? -1. : c;\n\n\tdouble theta = acos(c);\n\n\tif (s < XEPS)\n\t{\n\t\tdouble t;\n\n\t\tif (c > 0)\n\t\t\trx = ry = rz = 0;\n\t\telse\n\t\t{\n\t\t\tt = (R(0, 0) + 1)*0.5;\n\t\t\trx = sqrt(std::max(t, 0.0));\n\t\t\tt = (R(1, 1) + 1)*0.5;\n\t\t\try = sqrt(std::max(t, 0.0)) * (R(0, 1) < 0 ? -1.0 : 1.0);\n\t\t\tt = (R(2, 2) + 1)*0.5;\n\t\t\trz = sqrt(std::max(t, 0.0)) * (R(0, 2) < 0 ? -1.0 : 1.0);\n\n\t\t\tif (fabs(rx) < fabs(ry) && fabs(rx) < fabs(rz) && (R(1, 2) > 0) != (ry*rz > 0))\n\t\t\t\trz = -rz;\n\t\t\ttheta /= sqrt(rx*rx + ry*ry + rz*rz);\n\t\t\trx *= theta;\n\t\t\try *= theta;\n\t\t\trz *= theta;\n\t\t}\n\t}\n\telse\n\t{\n\t\tdouble vth = 1 / (2 * s);\n\t\tvth *= theta;\n\t\trx *= vth; ry *= vth; rz *= vth;\n\t}\n\treturn Eigen::Vector3d(rx, ry, rz).cast();\n}\n\nGeoTransform calibrateHandEye(std::vector& vH_robot, std::vector& vH_mark, HandEyeType t)\n{\n\t//Eigen::Matrix4f rt;\n\tconst int n = lxmin(vH_robot.size(), vH_mark.size());\n\tif(n <3)\n\t{\n\t\tprintf(\"At lease 3 point-pairs.\\n\");\n\t\treturn GeoTransform();\n\t}\n\n\tprintf(\"Start to calibrate with %d point-pairs.\\n\", n);\n \n\tstd::vector vA, vB;\n\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tfor (int j = i + 1; j < n; ++j)\n\t\t{\n\t\t\t//if(i == 0 && j==i+1) continue;\n\t\t\tif (t == EyeToHand)\n\t\t\t{\n\t\t\t\tGeoTransform A = vH_robot[j] * vH_robot[i].inverse();\n\t\t\t\tGeoTransform B = vH_mark[j] * vH_mark[i].inverse();\t\t\t \n\n\t\t\t\tvA.push_back(A);\n\t\t\t\tvB.push_back(B);\n\t\t\t}\n\t\t\telse if (t == EyeInHand)\n\t\t\t{\n\n\t\t\t\tGeoTransform A = vH_robot[j].inverse() * vH_robot[i];\n\t\t\t\tGeoTransform B = vH_mark[j] * vH_mark[i].inverse();\n\n\t\t\t\tvA.push_back(A);\n\t\t\t\tvB.push_back(B);\n\t\t\t}\n\t\t}\n\t}\n\t\n\n\tGeoTransform H = sovleAXequalXB(vA, vB);\n\n \n\n\treturn H;\n}\n\n\nEigen::MatrixXf svdInverse(Eigen::MatrixXf A)\n{\n\tEigen::JacobiSVD svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);//M=USV*\n\tfloat pinvtoler = 1.e-6; //tolerance\n\tint row = A.rows();\n\tint col = A.cols();\n\tint k = min(row, col);\n\tEigen::MatrixXf X = Eigen::MatrixXf::Zero(col, row);\n\tEigen::MatrixXf singularValues_inv = svd.singularValues();//奇异值\n\tEigen::MatrixXf singularValues_inv_mat = Eigen::MatrixXf::Zero(col, row);\n\tfor (long i = 0; i < k; ++i) {\n\t\tif (singularValues_inv(i) > pinvtoler)\n\t\t\tsingularValues_inv(i) = 1.0 / singularValues_inv(i);\n\t\telse singularValues_inv(i) = 0;\n\t}\n\tfor (long i = 0; i < k; ++i)\n\t{\n\t\tsingularValues_inv_mat(i, i) = singularValues_inv(i);\n\t}\n\tX = (svd.matrixV())*(singularValues_inv_mat)*(svd.matrixU().transpose());//X=VS+U*\n\n\treturn X;\n}\n\nGeoTransform sovleAXequalXB(std::vector& vA, std::vector& vB)\n{\n\tGeoTransform H;\n\tH.setIdentity();\n\tif (vA.size() != vB.size())\n\t{\n\t\tprintf(\"A and B must be same size.\\n\");\n\t\treturn H;\n\t}\n\n\tconst int n = vA.size();\n\n\tRotMat R_a, R_b;\n\tGeo3d r_a, r_b;\n\n\tEigen::MatrixXf A(n*3, 3);\n\tEigen::MatrixXf b(n*3, 1);\n\tA.setZero();\n\tb.setZero(); \n\n\tfor (int i = 0; i < n; ++i)\n\t{\n\t\tR_a = vA[i].linear();\n\t\tR_b = vB[i].linear();\n\t\t\n\t\tGeo3d rod_a = rodrigues2(R_a);\n\t\tGeo3d rod_b = rodrigues2(R_b);\n\n\t\tfloat theta_a = rod_a.norm();\n\t\tfloat theta_b = rod_b.norm();\n\n\t\trod_a /= theta_a;\n\t\trod_b /= theta_b;\n\n\t\tGeo3d P_a = 2*sin(theta_a/2)*rod_a;\n\t\tGeo3d P_b = 2*sin(theta_b/2)*rod_b;\t\t \n\n\t\tEigen::Matrix3f rot = skew(Geo3d(P_b+P_a));\n\t\tGeo3d v = P_b - P_a;\n\t\t//for (int row = 3 * i; row < 3 * i + 3; ++row)\n\t\t//{\n\t\t//\tfor (int col = 0; col < 3; ++col)\n\t\t//\t{\n\t\t//\t\tA(row, col) = rot(row - 3 * i, col);\n\t\t//\t}\n\n\t\t//\tb(row) = v(row - 3 * i);\n\t\t//}\n\n\t\t//cout << A.middleRows(3 * i, 3 * i + 3) << endl;\n\t\t//cout << rot << endl;\n\t\tA.middleRows(3 * i, 3) = rot;\n\t\tb.middleRows(3*i, 3) = v;\n\t}\n\t//Eigen::JacobiSVD svd(A, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n\t// 3 by 3*n \n\tEigen::MatrixXf pinA = svdInverse(A); \n\n\t// 3 by 1 = 3 by 3*n multi 3*n by 1\n\tGeo3d H_ba_prime = pinA * b;\n\t \n\tGeo3d H_ba = 2 * H_ba_prime / sqrt(1 + lxsq(H_ba_prime.norm()));\n\n\t// 1 by 3\n\tEigen::MatrixXf H_ba_Trs = H_ba.transpose();\n\n\tRotMat R_ba = (1 - lxsq(H_ba.norm()) / 2) * RotMat::Identity() \n\t\t+ 0.5 * (H_ba * H_ba_Trs + sqrt(4 - lxsq(H_ba.norm()))*skew(H_ba));\n\t\n\n\tA.setZero();\n\tb.setZero();\n\tfor (int i = 0; i < n; ++i)\n\t{\n\t\tRotMat AA = vA[i].linear() - RotMat::Identity();\n\t\tGeo3d bb = R_ba * vB[i].translation() - vA[i].translation();\n\t\t//for (int row = 3 * i; row < 3 * i + 3; ++row)\n\t\t//{\n\t\t//\tfor (int col = 0; col < 3; ++col)\n\t\t//\t{\n\t\t//\t\tA(row, col) = AA(row - 3 * i, col);\n\t\t//\t}\n\n\t\t//\tb(row) = bb(row - 3 * i);\n\t\t//}\n\t\tA.middleRows(3 * i, 3) = AA;\n\t\tb.middleRows(3 * i, 3) = bb;\n\t}\n\tpinA = svdInverse(A);\n\tGeo3d t_ba = pinA * b;\n\tH.linear() = R_ba;\n\tH.translation() = t_ba;\n\n\t// check\n\tfor(int i = 0; i\n#include \n#include // For non-member functions of distributions\n\n#include \n#include \nusing namespace std;\n\n\nint main()\n{\n\t// Don't forget to tell compiler which namespace\n\tusing namespace boost::math;\n\n\tnormal_distribution<> myNormal(1.0, 10.0); // Default type is 'double'\n\tcout << \"Mean: \" << mean(myNormal) << \", standard deviation: \" << standard_deviation(myNormal) << endl;\n\n\t// Distributional properties\n\tdouble x = 10.25;\n\n\tcout << \"pdf: \" << pdf(myNormal, x) << endl;\n\tcout << \"cdf: \" << cdf(myNormal, x) << endl;\n\n\t// Choose another data type and now a N(0,1) variate\n\tnormal_distribution myNormal2; \n\tcout << \"Mean: \" << mean(myNormal2) << \", standard deviation: \" << standard_deviation(myNormal2) << endl;\n\t\n\tcout << \"pdf: \" << pdf(myNormal2, x) << endl;\n\tcout << \"cdf: \" << cdf(myNormal2, x) << endl;\n\n\t// Choose precision\n\tcout.precision(10); // Number of values behind the comma\n\n\t// Other properties\n\tcout << \"\\n***normal distribution: \\n\";\n\tcout << \"mean: \" << mean(myNormal) << endl;\n\tcout << \"variance: \" << variance(myNormal) << endl;\n\tcout << \"median: \" << median(myNormal) << endl;\n\tcout << \"mode: \" << mode(myNormal) << endl;\n\tcout << \"kurtosis excess: \" << kurtosis_excess(myNormal) << endl;\n\tcout << \"kurtosis: \" << kurtosis(myNormal) << endl;\n\tcout << \"characteristic function: \" << chf(myNormal, x) << endl;\n\tcout << \"hazard: \" << hazard(myNormal, x) << endl;\n\n\t// Gamma distribution\n\tdouble alpha = 3.0; // Shape parameter, k\n\tdouble beta = 0.5;\t// Scale parameter, theta\n\tgamma_distribution myGamma(alpha, beta);\n\n\tdouble val = 13.0;\n\tcout << endl << \"pdf: \" << pdf(myGamma, val) << endl;\n\tcout << \"cdf: \" << cdf(myGamma, val) << endl;\n\n\tvector pdfList;\n\tvector cdfList;\n\n\tdouble start = 0.0;\n\tdouble end = 10.0;\n\tlong N = 30;\t\t// Number of subdivisions\n\n\tval = 0.0;\n\tdouble h = (end - start) / double(N);\n\n\tfor (long j = 1; j <= N; ++j)\n\t{\n\t\tpdfList.push_back(pdf(myGamma, val));\n\t\tcdfList.push_back(cdf(myGamma, val));\n\n\t\tval += h;\n\t}\n\n\tfor (long j = 0; j < pdfList.size(); ++j)\n\t{\n\t\tcout << pdfList[j] << \", \";\n\n\t}\n\n\tcout << \"***\" << endl;\n\n\tfor (long j = 0; j < cdfList.size(); ++j)\n\t{\n\t\tcout << cdfList[j] << \", \";\n\n\t}\n\n\treturn 0;\n}", "meta": {"hexsha": "1ae9ce8c6e09f23661ca7ce2af85be924469c0f2", "size": 2598, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Level_8/V. An Introduction to the Boost C++ Libraries/05b - Normal Distribution/TestNormalDistribution.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_8/V. An Introduction to the Boost C++ Libraries/05b - Normal Distribution/TestNormalDistribution.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_8/V. An Introduction to the Boost C++ Libraries/05b - Normal Distribution/TestNormalDistribution.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": 25.98, "max_line_length": 106, "alphanum_fraction": 0.6304849885, "num_tokens": 777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810421953309, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7561870236355397}} {"text": "/**\r\n * @file diffusion.hpp\r\n * @brief Collections of diffusion problem, definitions.\r\n * @author Francois Roy\r\n * @date 12/01/2019\r\n */\r\n#ifndef DIFFUSION_H\r\n#define DIFFUSION_H\r\n\r\n#include \r\n#include \r\n#include \"spdlog/spdlog.h\"\r\n#include \"numerical/fdm/fdm.hpp\"\r\n\r\nnamespace bench{\r\nnamespace diffusion{\r\n\r\ntypedef Eigen::VectorXd Vec;\r\ntypedef Eigen::ArrayXd Arr;\r\n\r\n/**\r\n* Reference solution for the 1D diffusion problem a, defined as:\r\n*\r\n* \\f[\r\n* \\frac{\\partial u}{\\partial t} = -\\alpha \\frac{\\partial^2 u}{\\partial x^2}\r\n* + f(x,t)\\quad x \\in (0, L),~t \\in (0, T]\r\n* \\f]\r\n*\r\n* with Dirichlet boundary condition \\f$u(0, t) = 0\\f$ and \\f$ u(L, t) = 0\\f$\r\n* for \\f$t>0\\f$.\r\n*\r\n* The diffusion coefficient, \\f$ \\alpha(L, t) = 1\\f$ is constant and uniform.\r\n*\r\n* We define the source term and initial condition with a reference \r\n* (manufactured) solution that respects the boundary conditions at the \r\n* extremities of the interval:\r\n*\r\n* \\f[\r\n* u(x, t) = 5tx*\\left(L-x\\right)\r\n* \\f]\r\n*\r\n* We get the source term substituting the manufactured solution in the \r\n* diffusion equation, i.e.:\r\n*\r\n* \\f[ \r\n* f(x, t) = 5x\\left(L-x\\right)+10\\alpha t\r\n* \\f]\r\n*\r\n* The initial condition is simply set to the manufactured solution at \r\n* \\f$t=0\\f$:\r\n*\r\n* \\f[ \r\n* u(x, 0) = u_0 = 0\r\n* \\f] \r\n*\r\n* @param x The spatial mesh node.\r\n* @param t The temporal mesh node.\r\n* @param L The length of the interval.\r\n* @return The reference solution.\r\n*/\r\ntemplate\r\nT reference_diffusion_a(T x, T t, T L){\r\n\treturn 5.0 * t * x * (L - x);\r\n}\r\n\r\n/**\r\n* Computes the 1D diffusion problem defined in @ref reference_diffusion_a() \r\n* using the finite difference method. Here we solve the problem using the\r\n* \\f$\\Theta\\f$-scheme in time and a centered difference scheme in space, i.e.\r\n*\r\n* \\f[\r\n* u_i^{n+1} - \\Theta\\left(\\alpha\\left(\r\n* \\frac{u_{i-1}^{n+1}-2u_{i}^{n+1}+u_{i+1}^{n+1}}{\\Delta x^2}\r\n* \\right)\\right) = \\left(1-\\Theta\\right)\\left(\\alpha\\left(\r\n* \\frac{u_{i-1}^{n}-2u_{i}^{n}+u_{i+1}^{n}}{\\Delta x^2}\r\n* \\right)\\right) + \\Theta\\Delta t f_i^{n+1}+\\left(1-\\Theta\\right)f_i^n\r\n* + u_i^n\r\n* \\f]\r\n*\r\n* For \\f$\\Theta=0\\f$ we have the forward Euler scheme in time, for \r\n* \\f$\\Theta=1\\f$ we have the backward Euler scheme in time and for \r\n* \\f$\\Theta=1/2\\f$ we have the Crank-Nicolson scheme in time.\r\n*\r\n* In matrix form we have:\r\n*\r\n* \\f[\r\n* \\mathbf{A}\\mathbf{u} = \\mathbf{b}\r\n* \\f]\r\n*\r\n* Using the Fourrier coefficient \\f$F=\\alpha\\Delta t/\\Delta x^2\\f$, the matrix\r\n* entries are:\r\n*\r\n* \\f[\r\n* A_{i,i-1}=-F\\Theta,~A{i, i}=1+2F\\Theta,~A_{i, i+1}=-F\\Theta\r\n* \\f].\r\n*\r\n* The vector \\f$\\mathbf{u}\\f$ represents the unknown at the discrete time \r\n* \\f$t=t^{n+1}\\f$.\r\n*\r\n* The RHS can be written as:\r\n*\r\n* \\f[\r\n* b_i = u_i^n + F\\left(1-\\Theta\\right)u_{i+1}^n-2u_i^n+u_{i-1}^n +\r\n* \\Delta t \\Theta f_i^{n+1} + \\Delta t \\left(1-\\Theta\\right)f_i^n\r\n* \\f]\r\n*\r\n* For more information see pp. 181-183 of:\r\n*\r\n* R. J. Leveque, Finite Difference Methods for Ordinary and Partial \r\n* Differential Equations: Steady-State and Time-Dependent Problems, SIAM, 2007.\r\n*\r\n* @return The solution.\r\n* @see numerical::fdm::Parameters\r\n* @see numerical::fdm::Mesh\r\n* @see numerical::fdm::SparseSolver\r\n*/\r\nbool fdm_diffusion_a();\r\n\r\nclass FDMDiffusionA : public numerical::fdm::Problem{\r\npublic:\r\n FDMDiffusionA(numerical::fdm::Parameters* p): \r\n numerical::fdm::Problem(p){\r\n }\r\n // double alpha(double x, double y, double z, double t);\r\n \r\n};\r\n\r\n} // namespace diffusion\r\n} // namespace bench\r\n\r\n#endif // DIFFUSION_H\r\n", "meta": {"hexsha": "bbd3f3b4bd2a0710bdddb62616e5d54e000a6621", "size": 3681, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "bench/diffusion/diffusion.hpp", "max_stars_repo_name": "dbeat/numerical", "max_stars_repo_head_hexsha": "bce26eb7d537eb8e32105f2887ea11940ce4fc96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bench/diffusion/diffusion.hpp", "max_issues_repo_name": "dbeat/numerical", "max_issues_repo_head_hexsha": "bce26eb7d537eb8e32105f2887ea11940ce4fc96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bench/diffusion/diffusion.hpp", "max_forks_repo_name": "dbeat/numerical", "max_forks_repo_head_hexsha": "bce26eb7d537eb8e32105f2887ea11940ce4fc96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8863636364, "max_line_length": 80, "alphanum_fraction": 0.6077152948, "num_tokens": 1224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.8757869916479466, "lm_q1q2_score": 0.7561471530268621}} {"text": "#include \"RegressionEigen.hpp\"\n#include \"RegressionGSL.hpp\"\n#include \n#include \n\n//#define EIGEN_USE_MKL_ALL\n//#define EIGEN_USE_BLAS // Enables openblas64\n#include \n\n \nusing namespace std; \nusing namespace Eigen;\nusing namespace EnjoLib;\n\nRegressionEigen::RegressionEigen(){}\nRegressionEigen::~RegressionEigen(){}\n\n/*\nVecD RegressionEigen::polynomialfit(int degree, const VecD & dx, const VecD & dy) const\n{\n return RegressionGSL().polynomialfit(degree, dx, dy);\n}\n*/\n\nVecD RegressionEigen::polynomialfit(int degree, const VecD & dx, const VecD & dy) const\n{\n VecD coeffs(degree);\n const int obs = dx.size();\n //VecD weights(obs);\n MatrixXd A(obs, degree);\n //cout << \"Here is the matrix A:\\n\" << A << endl;\n VectorXd b(obs);\n //Map b(dy.data(), obs, 1);\n //VecD dycopy = dy;\n //Map b(dycopy.data(), obs);\n const GeneralMath gmat;\n\n for(int i=0; i < obs; ++i)\n {\n b(i) = dy[i];\n \n //gsl_vector_set(y.vec, i, dy[i]);\n //gsl_vector_set(w.vec, i, weights[i]);\n //gsl_vector_set(w.vec, i, i); // More weight to latest\n //gsl_vector_set(w.vec, i, obs - i); // More weight to initial\n //gsl_vector_set(w.vec, i, 1); // Disabled different weights\n for(int j=0; j < degree; ++j)\n {\n //gsl_matrix_set(X.mat, i, j, pow(dx[i], j));\n A(i, j) = gmat.PowInt(dx[i], j);\n //A(i, j) = dx[i];\n }\n }\n \n /*\n const auto & eigRes = A.bdcSvd(ComputeThinU | ComputeThinV).solve(b);\n cout << \"The least-squares solution is:\\n\"\n << eigRes << endl;\n */ \n //const MatrixXd & aTrans = A.transpose();\n\t//const auto & f = (aTrans*A).inverse()*aTrans*b;\n\tconst auto & f = (A.transpose()*A).inverse()*A.transpose()*b; // Faster\n\t\n\t// Faster!\n\t//const auto & f = (A.transpose()*A).inverse()*A.transpose()*b;\n\t//const auto & ff = A.colPivHouseholderQr().solve(b);\n\t//const auto & ff = A.bdcSvd(ComputeThinU | ComputeThinV).solve(b);\n\t\n\t//cout << \"Matrix f\" << endl;\n\t//cout << ff << endl;\n\n /* store result ... */\n for(int i=0; i < degree; ++i)\n {\n const double coeff = f(i, 0);\n //cout << \"Coeff \" << i << \" = \" << coeff << endl;;\n coeffs[i] = coeff;\n }\n return coeffs; /* we do not \"analyse\" the result (cov matrix mainly)\n to know if the fit is \"good\" */\n // http://stats.stackexchange.com/questions/151018/how-does-the-covariance-matrix-of-a-fit-get-computed\n}", "meta": {"hexsha": "09fcc845c212903b3a3e0a413437dbd3ae2b6a5f", "size": 2535, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libStat3rd/Statistical/3rdParty/RegressionEigen.cpp", "max_stars_repo_name": "EnjoMitch/EnjoLib", "max_stars_repo_head_hexsha": "321167146657cba1497a9d3b4ffd71430f9b24b3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T15:36:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T15:16:08.000Z", "max_issues_repo_path": "libStat3rd/Statistical/3rdParty/RegressionEigen.cpp", "max_issues_repo_name": "EnjoMitch/EnjoLib", "max_issues_repo_head_hexsha": "321167146657cba1497a9d3b4ffd71430f9b24b3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-17T07:52:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-17T07:52:15.000Z", "max_forks_repo_path": "libStat3rd/Statistical/3rdParty/RegressionEigen.cpp", "max_forks_repo_name": "EnjoMitch/EnjoLib", "max_forks_repo_head_hexsha": "321167146657cba1497a9d3b4ffd71430f9b24b3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-07-12T14:52:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-28T17:10:33.000Z", "avg_line_length": 30.9146341463, "max_line_length": 107, "alphanum_fraction": 0.5854043393, "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873763, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.756120102346626}} {"text": "/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */\n#include \"runtime/matrix.h\"\n\n#include \n\n#include \n#include \n#include \n\nusing Eigen::Map;\nusing Eigen::Matrix3d;\nusing Eigen::MatrixXd;\nusing Eigen::Vector3d;\nusing Eigen::VectorXd;\n\nnamespace flint {\nnamespace runtime {\n\nvoid Transpose(double *d0, const double *d1, int kr, int kc)\n{\n\tMap m0(d0, kr, kc);\n\tMap m1(d1, kc, kr);\n\tm0 = m1.transpose();\n}\n\nvoid Outerproduct(double *d0,\n\t\t\t\t int k1, const double *d1,\n\t\t\t\t int k2, const double *d2)\n{\n\tMap v1(d1, k1);\n\tMap v2(d2, k2);\n\tMap m0(d0, k2, k1);\n\tm0.noalias() = v1 * v2.transpose();\n}\n\ndouble Scalarproduct(int k, const double *d1, const double *d2)\n{\n\tMap v1(d1, k);\n\tMap v2(d2, k);\n\treturn v1.dot(v2);\n}\n\nvoid Vectorproduct(double *d0, const double *d1, const double *d2)\n{\n\tMap v0(d0);\n\tMap v1(d1);\n\tMap v2(d2);\n\tv0 = v1.cross(v2);\n}\n\ndouble Determinant(int k, const double *d1)\n{\n\tMap m1(d1, k, k);\n\treturn m1.determinant();\n}\n\ndouble Select2(const double *d1, int n2)\n{\n\tassert(n2 > 0); // 1-based\n\treturn d1[n2 - 1];\n}\n\ndouble Select3(int kr, int kc, const double *d1, int n2, int n3)\n{\n\tassert(n2 > 0);\n\tassert(n3 > 0);\n\tMap m1(d1, kr, kc);\n\treturn m1(n2 - 1, n3 - 1);\n}\n\nvoid Selrow(double *d0, int kr, int kc, const double *d1, int n2)\n{\n\tassert(n2 > 0); // 1-based\n\tMap v0(d0, kr);\n\tMap m1(d1, kr, kc);\n\tv0 = m1.row(n2 - 1);\n}\n\nvoid Mult(double *d0, int k, double a1, const double *d2)\n{\n\tMap v0(d0, k);\n\tMap v2(d2, k);\n\tv0.noalias() = a1 * v2;\n}\n\nvoid Mmul(double *d0, int kr, int kx, int kc,\n\t\t const double *d1, const double *d2)\n{\n\tMap m0(d0, kr, kc);\n\tMap m1(d1, kr, kx);\n\tMap m2(d2, kx, kc);\n\tm0.noalias() = m1 * m2;\n}\n\n}\n}\n", "meta": {"hexsha": "c3530d687f0fa74e0ecb57b2cab30f9c7c87d05b", "size": 2021, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/runtime/matrix.cc", "max_stars_repo_name": "Abhisheknishant/Flint", "max_stars_repo_head_hexsha": "441beab56d21e4069b858ae6588fa0fa3084d722", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-09-07T05:33:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T03:35:08.000Z", "max_issues_repo_path": "src/runtime/matrix.cc", "max_issues_repo_name": "Abhisheknishant/Flint", "max_issues_repo_head_hexsha": "441beab56d21e4069b858ae6588fa0fa3084d722", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-03-19T02:10:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T08:20:51.000Z", "max_forks_repo_path": "src/runtime/matrix.cc", "max_forks_repo_name": "Abhisheknishant/Flint", "max_forks_repo_head_hexsha": "441beab56d21e4069b858ae6588fa0fa3084d722", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-03-26T00:32:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-11T23:21:42.000Z", "avg_line_length": 20.8350515464, "max_line_length": 107, "alphanum_fraction": 0.6447303315, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768588653855, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7559948617028396}} {"text": "#include \r\n#include \r\n#include \r\n#include \"stiffness_matrix.hpp\"\r\n\r\nTEST(TestStiffnessMatrix, TestReferenceElement) {\r\n Eigen::MatrixXd vertices(3, 3);\r\n vertices << 0, 0, 0,\r\n 1, 0, 0,\r\n 0, 1, 0;\r\n \r\n Eigen::Matrix3d stiffnessMatrix;\r\n\r\n\r\n computeStiffnessMatrix(stiffnessMatrix, vertices.row(0), vertices.row(1), vertices.row(2));\r\n\r\n // This should be equal to\r\n // \r\n // int_K grad lambda(0, x) * grad lambda(0, x) dx = 1\r\n // \r\n // where K is the triangle spanned by (0,0), (1,0), (1,0)\r\n const double expected00 = 1;\r\n ASSERT_NEAR(expected00, stiffnessMatrix(0, 0), 1e-8) << \"stiffness matrix vector not correct at (0,0)\";\r\n\r\n\r\n // This should be equal to\r\n // \r\n // int_K grad lambda(0, x) * grad lambda(1, x) dx = -0.5\r\n // \r\n // where K is the triangle spanned by (0,0), (1,0), (1,0)\r\n const double expected01 = -0.5;\r\n ASSERT_NEAR(expected01, stiffnessMatrix(0, 1), 1e-8) << \"stiffness matrix vector not correct at (0,1)\";\r\n\r\n // This should be equal to\r\n // \r\n // int_K grad lambda(0, x) * grad lambda(2, x) dx = -0.5\r\n // \r\n // where K is the triangle spanned by (0,0), (1,0), (1,0)\r\n const double expected02 = -0.5;\r\n ASSERT_NEAR(expected02, stiffnessMatrix(0, 2), 1e-8) << \"stiffness matrix vector not correct at (0,2)\";\r\n\r\n // This should be equal to\r\n // \r\n // int_K grad lambda(1, x) * grad lambda(0, x) dx = -0.5\r\n // \r\n // where K is the triangle spanned by (0,0), (1,0), (1,0)\r\n const double expected10 = -0.5;\r\n ASSERT_NEAR(expected10, stiffnessMatrix(1, 0), 1e-8) << \"stiffness matrix vector not correct at (1,0)\";\r\n\r\n\r\n // This should be equal to\r\n // \r\n // int_K grad lambda(1, x) * grad lambda(1, x) dx = 0.5\r\n // \r\n // where K is the triangle spanned by (0,0), (1,0), (1,0)\r\n const double expected11 = 0.5;\r\n ASSERT_NEAR(expected11, stiffnessMatrix(1, 1), 1e-8) << \"stiffness matrix vector not correct at (1,1)\";\r\n\r\n // This should be equal to\r\n // \r\n // int_K grad lambda(1, x) * grad lambda(2, x) dx = 0\r\n // \r\n // where K is the triangle spanned by (0,0), (1,0), (1,0)\r\n const double expected12 = 0;\r\n ASSERT_NEAR(expected12, stiffnessMatrix(1, 2), 1e-8) << \"stiffness matrix vector not correct at (1,2)\";\r\n\r\n\r\n // This should be equal to\r\n // \r\n // int_K grad lambda(2, x) * grad lambda(0, x) dx = -0.5\r\n // \r\n // where K is the triangle spanned by (0,0), (1,0), (1,0)\r\n const double expected20 = -0.5;\r\n ASSERT_NEAR(expected20, stiffnessMatrix(2, 0), 1e-8) << \"stiffness matrix vector not correct at (2, 0)\";\r\n\r\n\r\n // This should be equal to\r\n // \r\n // int_K grad lambda(2, x) * grad lambda(1, x) dx = 0\r\n // \r\n // where K is the triangle spanned by (0,0), (1,0), (1,0)\r\n const double expected21 = 0;\r\n ASSERT_NEAR(expected21, stiffnessMatrix(2, 1), 1e-8) << \"stiffness matrix vector not correct at (2,1)\";\r\n\r\n // This should be equal to\r\n // \r\n // int_K grad lambda(1, x) * grad lambda(2, x) dx = 0.5\r\n // \r\n // where K is the triangle spanned by (0,0), (1,0), (1,0)\r\n const double expected22 = 0.5;\r\n ASSERT_NEAR(expected22, stiffnessMatrix(2, 2), 1e-8) << \"stiffness matrix vector not correct at (2,2)\";\r\n}\r\n\r\n\r\nTEST(TestStiffnessMatrix, TestSkewTriagnle) {\r\n Eigen::MatrixXd vertices(3, 3);\r\n vertices << 0, 0, 0,\r\n 1, 0.4, 0,\r\n 0, 1, 0;\r\n\r\n Eigen::Matrix3d stiffnessMatrix;\r\n\r\n computeStiffnessMatrix(stiffnessMatrix, vertices.row(0), vertices.row(1), vertices.row(2));\r\n\r\n // This should be equal to\r\n // \r\n // int_K grad lambda(0, x) * grad lambda(0, x) dx = 0.68\r\n // \r\n // where K is the triangle spanned by (0,0), (1,0.4), (1,0)\r\n const double expected00 = 0.68;\r\n ASSERT_NEAR(expected00, stiffnessMatrix(0, 0), 1e-8) << \"stiffness matrix vector not correct at (0,0)\";\r\n\r\n\r\n // This should be equal to\r\n // \r\n // int_K grad lambda(0, x) * grad lambda(1, x) dx = -0.3\r\n // \r\n // where K is the triangle spanned by (0,0), (1,0.4), (1,0)\r\n const double expected01 = -0.3;\r\n ASSERT_NEAR(expected01, stiffnessMatrix(0, 1), 1e-8) << \"stiffness matrix vector not correct at (0,1)\";\r\n\r\n // This should be equal to\r\n // \r\n // int_K grad lambda(0, x) * grad lambda(2, x) dx = -0.38\r\n // \r\n // where K is the triangle spanned by (0,0), (1,0.4), (1,0)\r\n const double expected02 = -0.38;\r\n ASSERT_NEAR(expected02, stiffnessMatrix(0, 2), 1e-8) << \"stiffness matrix vector not correct at (0,2)\";\r\n\r\n // This should be equal to\r\n // \r\n // int_K grad lambda(1, x) * grad lambda(0, x) dx = -0.3\r\n // \r\n // where K is the triangle spanned by (0,0), (1,0.4), (1,0)\r\n const double expected10 = -0.3;\r\n ASSERT_NEAR(expected10, stiffnessMatrix(1, 0), 1e-8) << \"stiffness matrix vector not correct at (1,0)\";\r\n\r\n\r\n // This should be equal to\r\n // \r\n // int_K grad lambda(1, x) * grad lambda(1, x) dx = 0.5\r\n // \r\n // where K is the triangle spanned by (0,0), (1,0.4), (1,0)\r\n const double expected11 = 0.5;\r\n ASSERT_NEAR(expected11, stiffnessMatrix(1, 1), 1e-8) << \"stiffness matrix vector not correct at (1,1)\";\r\n\r\n // This should be equal to\r\n // \r\n // int_K grad lambda(1, x) * grad lambda(2, x) dx = 0.2\r\n // \r\n // where K is the triangle spanned by (0,0), (1,0.4), (1,0)\r\n const double expected12 = -0.2;\r\n ASSERT_NEAR(expected12, stiffnessMatrix(1, 2), 1e-8) << \"stiffness matrix vector not correct at (1,2)\";\r\n\r\n\r\n // This should be equal to\r\n // \r\n // int_K grad lambda(2, x) * grad lambda(0, x) dx = -0.38\r\n // \r\n // where K is the triangle spanned by (0,0), (1,0.4), (1,0)\r\n const double expected20 = -0.38;\r\n ASSERT_NEAR(expected20, stiffnessMatrix(2, 0), 1e-8) << \"stiffness matrix vector not correct at (2, 0)\";\r\n\r\n\r\n // This should be equal to\r\n // \r\n // int_K grad lambda(2, x) * grad lambda(1, x) dx = -0.2\r\n // \r\n // where K is the triangle spanned by (0,0), (1,0.4), (1,0)\r\n const double expected21 = -0.2;\r\n ASSERT_NEAR(expected21, stiffnessMatrix(2, 1), 1e-8) << \"stiffness matrix vector not correct at (2,1)\";\r\n\r\n // This should be equal to\r\n // \r\n // int_K grad lambda(1, x) * grad lambda(2, x) dx = 0.58\r\n // \r\n // where K is the triangle spanned by (0,0), (1,0.4), (1,0)\r\n const double expected22 = 0.58;\r\n ASSERT_NEAR(expected22, stiffnessMatrix(2, 2), 1e-8) << \"stiffness matrix vector not correct at (2,2)\";\r\n}\r\n", "meta": {"hexsha": "67cdbddd5caa5985fc9bbd5d2d06e77f53b33e1f", "size": 6565, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series0_solution/2d-poissonlFEM/unittest/TestStiffnessMatrix.cpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series0_solution/2d-poissonlFEM/unittest/TestStiffnessMatrix.cpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series0_solution/2d-poissonlFEM/unittest/TestStiffnessMatrix.cpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 36.270718232, "max_line_length": 109, "alphanum_fraction": 0.5762376238, "num_tokens": 2253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921841290738, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7558775718787896}} {"text": "/**\n * @file useGeometry.cpp\n * @date 2017/9/8\n * @version V1.0\n * @author Jacob.lin\n */\n\n#include \n#include \nusing namespace std;\n\n#include \n#include \nusing namespace Eigen;\n\nint main(int argc, char **argv)\n{\n argc = (int)argc;\n argv = (char **)argv;\n \n Eigen::Matrix3d rotation_matrix = Eigen::Matrix3d::Identity();\n Eigen::AngleAxisd rotation_vector(M_PI/4, Eigen::Vector3d(0, 0, 1));\n \n cout.precision(3);\n cout << \"rotation_matrix = \\r\\n\" << rotation_vector.matrix() << endl;\n \n rotation_matrix = rotation_vector.toRotationMatrix();\n \n Eigen::Vector3d v(1, 0, 0);\n Eigen::Vector3d v_rotation = rotation_vector * v;\n cout << \"(1, 0, 0) after rotation = \" << v_rotation.transpose() << endl;\n \n v_rotation = rotation_matrix * v;\n cout << \"(1, 0, 0) after rotation = \" << v_rotation.transpose() << endl;\n \n Eigen::Vector3d euler_angles = rotation_matrix.eulerAngles(2, 1, 0); /* 2,1,0 is ZYX axis, yaw, pitch, roll */\n cout << \"yaw pitch roll = \" << euler_angles.transpose();\n \n Eigen::Isometry3d T = Eigen::Isometry3d::Identity();\n T.rotate(rotation_vector);\n T.pretranslate(Eigen::Vector3d(1, 3, 4));\n cout << \"Transform matrix = \\r\\n\" << T.matrix() << endl;\n \n Eigen::Vector3d v_transformed = T * v;\n cout << \"v tranformed = \" << v_transformed.transpose() << endl;\n \n Eigen::Quaterniond q = Eigen::Quaterniond(rotation_vector);\n cout << \"quaternion = \\r\\n\" << q.coeffs() << endl;\n q = Eigen::Quaterniond(rotation_matrix);\n cout << \"quaternion = \\r\\n\" << q.coeffs() << endl;\n \n v_rotation = q * v; /* qvq^(-1) */\n cout << \"(1, 0, 0) after rotation = \" << v_rotation.transpose() << endl;\n \n return 0;\n}\n\n\n", "meta": {"hexsha": "d5f3a30d671253076e000ce3785f3a95b52edc94", "size": 1776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "useGeometry/src/useGeometry.cpp", "max_stars_repo_name": "LSXiang/slam_learning_journey", "max_stars_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-03-22T00:25:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-01T05:23:27.000Z", "max_issues_repo_path": "useGeometry/src/useGeometry.cpp", "max_issues_repo_name": "LSXiang/slam_learning_journey", "max_issues_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "useGeometry/src/useGeometry.cpp", "max_forks_repo_name": "LSXiang/slam_learning_journey", "max_forks_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1016949153, "max_line_length": 117, "alphanum_fraction": 0.6058558559, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7558564336606328}} {"text": "#include \n#include \n#include \n#include \n\nclass exp_func\n{\n public:\n exp_func(Eigen::Vector2d init) : x_0{init[0]}, y_0{init[1]} {}\n exp_func() {}\n \n double operator() (const Eigen::Vector2d x_) const\n {\n double x{x_[0]}, y{x_[1]};\n return std::exp(- std::pow(x - x_0, 2) - std::pow(y - y_0, 2));\n }\n\n double d_dx(const Eigen::Vector2d x_) const\n {\n double x{x_[0]}, y{x_[1]};\n return -2 * (x - this->x_0) * this->operator()(x_);\n }\n\n double d2_dx2(const Eigen::Vector2d x_) const\n {\n double x{x_[0]}, y{x_[1]};\n return (4 * (x - this->x_0) * (x - this->x_0) - 2) * this->operator()(x_);\n }\n double d_dy(const Eigen::Vector2d x_) const\n {\n double x{x_[0]}, y{x_[1]};\n return -2 * (y - this->y_0) * this->operator()(x_);\n }\n\n double d2_dy2(const Eigen::Vector2d x_) const\n {\n double x{x_[0]}, y{x_[1]};\n return (4 * (y - this->y_0) * (y - this->y_0) - 2) * this->operator()(x_);\n }\n\n double d2_dxdy(const Eigen::Vector2d x_) const\n {\n double x{x_[0]}, y{x_[1]};\n return 4 * (x - this->x_0) * (y - this->y_0) * this->operator()(x_);\n }\n\n double d2_dydx(const Eigen::Vector2d x_) const\n {\n return this->d2_dxdy(x_);\n }\n \n private:\n double x_0{0.0}, y_0{0.0};\n};\n\nclass F_func\n{\n public:\n F_func(Eigen::Vector2d init) : Fx(init), Fy(init) {}\n\n const Eigen::Vector2d operator() (const Eigen::Vector2d x_) const\n {\n return Eigen::Vector2d(Fx.d_dx(x_), Fy.d_dy(x_));\n }\n\n const Eigen::Matrix2d J(const Eigen::Vector2d x_) const\n {\n Eigen::Matrix2d J;\n J << Fx.d2_dx2 (x_), Fx.d2_dxdy(x_),\n Fx.d2_dydx(x_), Fx.d2_dy2 (x_);\n return J;\n }\n\n const Eigen::Matrix2d J_inv(const Eigen::Vector2d x_) const\n {\n return this->J(x_).inverse();\n }\n\n const Eigen::Matrix2d J_sec(const Eigen::Vector2d x_) const\n {\n const double h_x{x_[0] * std::sqrt(std::numeric_limits::epsilon())};\n const double h_y{x_[1] * std::sqrt(std::numeric_limits::epsilon())};\n const Eigen::Vector2d e_x{1.0, 0.0};\n const Eigen::Vector2d e_y{0.0, 1.0};\n\n Eigen::Matrix2d J_sec;\n J_sec << (this->operator()(x_ + h_x * e_x)[0] - this->operator()(x_)[0]) / h_x,\n (this->operator()(x_ + h_y * e_y)[0] - this->operator()(x_)[0]) / h_y,\n (this->operator()(x_ + h_x * e_x)[1] - this->operator()(x_)[1]) / h_x,\n (this->operator()(x_ + h_y * e_y)[1] - this->operator()(x_)[1]) / h_y;\n return J_sec;\n }\n\n const Eigen::Matrix2d J_sec_inv(const Eigen::Vector2d x_) const\n {\n return this->J_sec(x_).inverse();\n }\n\n private:\n exp_func Fx, Fy;\n};\n\ninline double dist(const Eigen::Vector2d a, \n const Eigen::Vector2d b = Eigen::Vector2d::Zero(2))\n{\n return std::sqrt((a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]));\n}\n\nint main(int argc, char* argv[])\n{\n if (argc < 5 || argc > 5 || argv[1] == \"-h\") // check cl args and give some help\n { \n std::cerr << \"Usage: \" << argv[0] << \"\\n\\t\"\n << \" x_0(double): parameter x_0\" << \"\\n\\t\"\n << \" y_0(double): parameter y_0\" << \"\\n\\t\"\n << \" x_init(double): initial x\" << \"\\n\\t\"\n << \" y_init(double): initial y\" << \"\\n\\t\"\n << std::endl << std::endl;\n return 1;\n }\n const double x_0{atof(argv[1])};\n const double y_0{atof(argv[2])};\n const Eigen::Vector2d init(x_0, y_0);\n\n const double x_start{atof(argv[3])};\n const double y_start{atof(argv[4])};\n const Eigen::Vector2d start(x_start, y_start);\n\n exp_func f(init);\n F_func F(init);\n\n // Newton-Raphson method\n Eigen::Vector2d x_n;\n Eigen::Vector2d x_np1{start - F.J_inv(start) * F(start)};\n\n std::cout << start[0] << \"\\t\" << start[1] << \"\\t\" << f(start) << std::endl;\n\n while (dist(F(x_np1)) > std::numeric_limits::epsilon())\n {\n x_n= x_np1;\n std::cout << x_n[0] << \"\\t\" << x_n[1] << \"\\t\" << f(x_n) << std::endl;\n x_np1= x_n - F.J_inv(x_n) * F(x_n);\n }\n\n std::cout << std::endl << std::endl;\n\n // Secant method\n x_np1= start - F.J_sec_inv(start) * F(start); \n\n std::cout << start[0] << \"\\t\" << start[1] << \"\\t\" << f(start) << std::endl;\n\n while (dist(F(x_np1)) > std::numeric_limits::epsilon())\n {\n x_n= x_np1;\n std::cout << x_n[0] << \"\\t\" << x_n[1] << \"\\t\" << f(x_n) << std::endl;\n x_np1= x_n - F.J_sec_inv(x_n) * F(x_n);\n }\n\n return 0;\n}", "meta": {"hexsha": "ac15acb4c674fbf79aefd6a97a12445a4cab7ff9", "size": 4973, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ex09/main.cpp", "max_stars_repo_name": "BeatHubmann/18H-ICP", "max_stars_repo_head_hexsha": "2ad1bcef73f3f43d832031cf45c4909341176ebd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ex09/main.cpp", "max_issues_repo_name": "BeatHubmann/18H-ICP", "max_issues_repo_head_hexsha": "2ad1bcef73f3f43d832031cf45c4909341176ebd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex09/main.cpp", "max_forks_repo_name": "BeatHubmann/18H-ICP", "max_forks_repo_head_hexsha": "2ad1bcef73f3f43d832031cf45c4909341176ebd", "max_forks_repo_licenses": ["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.08125, "max_line_length": 91, "alphanum_fraction": 0.488236477, "num_tokens": 1587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240211961401, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7557829043541866}} {"text": "//\n// Trilateration.cpp\n//\n// Created by waynewang on 19/4/14.\n// Copyright (c) 2014 waynewang. All rights reserved.\n//\n#pragma warning(push)\n#pragma warning(disable : 4244) // Disable warnings from external toolkit.\n#include \"Trilateration.h\"\n#include \n#include \n#pragma warning(pop)\n\nbool Trilateration::CalculateLocation2d(const PosAndDistance2dVec& beacons, Pos2d& location)\n{\n // To locate position on a 2d plan, have to get at least 3 becaons,\n // otherwise return false.\n if (beacons.size() < 3)\n return false;\n \n // Define the matrix that we are going to use\n size_t count = beacons.size();\n size_t rows = count * (count - 1) / 2;\n Eigen::MatrixXd m(rows, 2);\n Eigen::VectorXd b(rows);\n \n // Fill in matrix according to the equations\n size_t row = 0;\n double x1, x2, y1, y2, r1, r2;\n PosAndDistance2d beacon1, beacon2;\n for (size_t i=0; i\n#include \n\nvoid hTrans3dVec(const Eigen::Matrix& v,\n Eigen::Matrix& r,\n\t\tconst Eigen::Matrix& q,\n\t\tfloat theta)\n{\n\n Eigen::Matrix htMatrix;\n htMatrix << std::cos(theta), -std::sin(theta), 0.0, q[0],\n std::sin(theta), std::cos(theta), 0.0, q[1],\n\t 0.0, 0.0, 1.0, q[2],\n\t 0.0, 0.0, 0.0, 1.0;\n \n std::cout << \"v values:\\n\" << v << std::endl;\n std::cout << \"homogeneous transformation values:\\n\" << htMatrix << std::endl;\n\n r = htMatrix * v;\n\n}\n\nint main(int argc, char* argv[])\n{\n\n Eigen::Matrix v;\n Eigen::Matrix r;\n Eigen::Matrix Q;\n float theta;\n\n // init matrix\n v << 0.5, 0.5, 0.0, 1.0;\n Q << 1.0, 1.0, 0.0;\n theta = 00.523599; // 30 degree -> radian\n\n hTrans3dVec(v, r, Q, theta);\n\n std::cout << \"r:\\n\" << r << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "9b8cbb2abeb3086b36b467709d0f4260a335afcd", "size": 1393, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/examples/1/hTransformation_ex.cpp", "max_stars_repo_name": "jefersonjlima/robotics-codes", "max_stars_repo_head_hexsha": "6a15e29d53d1693bb08e590a40fac5b1c828c107", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/examples/1/hTransformation_ex.cpp", "max_issues_repo_name": "jefersonjlima/robotics-codes", "max_issues_repo_head_hexsha": "6a15e29d53d1693bb08e590a40fac5b1c828c107", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/examples/1/hTransformation_ex.cpp", "max_forks_repo_name": "jefersonjlima/robotics-codes", "max_forks_repo_head_hexsha": "6a15e29d53d1693bb08e590a40fac5b1c828c107", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3272727273, "max_line_length": 80, "alphanum_fraction": 0.4888729361, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7555547691969869}} {"text": "#include \n\n#include \n\n#include \n\n#include \"GaussLegendre.hh\"\n#include \"TypesFunctions.hh\"\n\nusing namespace Eigen;\n\nvoid GaussLegendre::init() {\n size_t npoints = 0;\n for (size_t n: m_orders) {\n npoints += n;\n }\n m_points.resize(npoints);\n m_weights.resize(npoints);\n //k stands for a bin number\n size_t k = 0;\n\n //simply allocates the weights and abscissae table of Gauss-Legendre n-point\n //integration rule\n //https://en.wikipedia.org/wiki/Gaussian_quadrature\n for (size_t i = 0; i < m_orders.size(); ++i) {\n size_t n = m_orders[i];\n auto *t = gsl_integration_glfixed_table_alloc(n);\n\n double a = m_edges[i];\n double b = m_edges[i+1];\n\n //actually provides the absc and weight. for interval [a,b] and store it\n //to m_points and m_weights,\n for (size_t j = 0; j < t->n; ++j) {\n gsl_integration_glfixed_point(a, b, j, &m_points[k], &m_weights[k], t);\n k++;\n }\n gsl_integration_glfixed_table_free(t);\n }\n //return only points, WTF?\n transformation_(\"points\")\n .output(\"x\")\n .output(\"xedges\")\n .output(\"xhist\")\n .types([](GaussLegendre *obj, TypesFunctionArgs& fargs) {\n auto& rets=fargs.rets;\n rets[0] = DataType().points().shape(obj->m_points.size());\n rets[1] = DataType().points().shape(obj->m_edges.size());\n rets[2] = DataType().hist().edges(obj->m_edges);\n })\n .func([](GaussLegendre *obj, FunctionArgs& fargs) {\n auto& rets=fargs.rets;\n rets[0].x = obj->m_points;\n rets[1].x = Eigen::Map(&obj->m_edges[0], obj->m_edges.size());\n })\n .finalize()\n ;\n}\n\nGaussLegendreHist::GaussLegendreHist(const GaussLegendre *base)\n : m_base(base)\n{\n transformation_(\"hist\")\n .input(\"f\")\n .output(\"hist\")\n .types(TypesFunctions::ifSame, [](GaussLegendreHist *obj, TypesFunctionArgs& fargs) {\n fargs.rets[0] = DataType().hist().bins(obj->m_base->m_orders.size()).edges(obj->m_base->m_edges);\n })\n .func([](GaussLegendreHist *obj, FunctionArgs& fargs) {\n auto& ret=fargs.rets[0].x;\n ArrayXd prod = fargs.args[0].x*obj->m_base->m_weights;\n auto *data = prod.data();\n const auto &orders = obj->m_base->m_orders;\n for (size_t i = 0; i < orders.size(); ++i) {\n size_t n = orders[i];\n ret(i) = std::accumulate(data, data+n, 0.0);\n data += n;\n }\n })\n ;\n}\n", "meta": {"hexsha": "1b8c7e1be63a058a4c724fe4bd986969d6c6ab68", "size": 2443, "ext": "cc", "lang": "C++", "max_stars_repo_path": "transformations/legacy/GaussLegendre.cc", "max_stars_repo_name": "gnafit/gna", "max_stars_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T16:33:06.000Z", "max_issues_repo_path": "transformations/legacy/GaussLegendre.cc", "max_issues_repo_name": "gnafit/gna", "max_issues_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "transformations/legacy/GaussLegendre.cc", "max_forks_repo_name": "gnafit/gna", "max_forks_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7926829268, "max_line_length": 105, "alphanum_fraction": 0.6119525174, "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7555117350100067}} {"text": "#pragma once\r\n#include \r\n\r\nnamespace Geometry {\r\n\r\n using Mat3 = Eigen::Matrix3f;\r\n using Vec3 = Eigen::Vector3f;\r\n\r\n namespace SO3 {\r\n // TODO: Exp, Log, boxplus, boxminus, interpolation\r\n\r\n inline\r\n Mat3 Exp(const Vec3& w) {\r\n Mat3 w_hat;\r\n w_hat <<\r\n 0, -w.z(), w.y(),\r\n w.z(), 0, -w.x(),\r\n -w.y(), w.x(), 0;\r\n // Note: e.g. w.cross(some_other_vector) == w_hat * some_other_vector;\r\n\r\n /*const double phi = w.norm(); // L2 norm\r\n\r\n return Mat3::Identity() +\r\n w_hat / phi * sin(phi) +\r\n w_hat * w_hat / (phi * phi) * (1 - cos(phi));*/\r\n\r\n const double phi2 = w.squaredNorm();\r\n\r\n if (phi2 > std::numeric_limits::epsilon()) {\r\n const double phi = std::sqrt(phi2);\r\n return Mat3::Identity() +\r\n w_hat / phi * sin(phi) +\r\n w_hat * w_hat / (phi * phi) * (1 - cos(phi));\r\n }\r\n else {\r\n return Mat3::Identity() + w_hat;\r\n }\r\n }\r\n\r\n inline\r\n Vec3 Log(const Mat3& R) {\r\n\r\n // question: how to improve? (homework) +1.0p\r\n const double phi = std::acos((R.trace() - 1) / 2);\r\n\r\n if (phi > std::numeric_limits::epsilon()) {\r\n Vec3 w_normalized = 1 / (2 * sin(phi)) * Vec3(\r\n R(2, 1) - R(1, 2),\r\n R(0, 2) - R(2, 0),\r\n R(1, 0) - R(0, 1)\r\n );\r\n\r\n return phi * w_normalized;\r\n }\r\n else {\r\n return (1.0 / 2.0) * Vec3(\r\n R(2, 1) - R(1, 2),\r\n R(0, 2) - R(2, 0),\r\n R(1, 0) - R(0, 1)\r\n );\r\n }\r\n }\r\n\r\n inline\r\n Vec3 boxminus(const Mat3& X, const Mat3& Y) {\r\n return Log(X * Y.transpose());\r\n }\r\n\r\n inline\r\n Mat3 boxplus(const Mat3& X, const Vec3& u) {\r\n return Exp(u) * X;\r\n }\r\n\r\n inline\r\n Mat3 interpolate(const Mat3& X, const Mat3& Y, const double& t) {\r\n // t == 0 -> Y\r\n // t == 1 -> X\r\n // t \\in (0,1) -> .....\r\n return boxplus(X, t * boxminus(Y, X));\r\n }\r\n\r\n }\r\n\r\n}", "meta": {"hexsha": "df901e2d692c5ebde0aae67a62b41f38d5a60f81", "size": 2014, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SO3.hpp", "max_stars_repo_name": "SohilZidan/point-cloud-registration", "max_stars_repo_head_hexsha": "5e7f52fbf04f3a58238a2c92393143d5e110c8e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SO3.hpp", "max_issues_repo_name": "SohilZidan/point-cloud-registration", "max_issues_repo_head_hexsha": "5e7f52fbf04f3a58238a2c92393143d5e110c8e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-11-27T17:52:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-28T07:04:05.000Z", "max_forks_repo_path": "SO3.hpp", "max_forks_repo_name": "SohilZidan/point-cloud-registration", "max_forks_repo_head_hexsha": "5e7f52fbf04f3a58238a2c92393143d5e110c8e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9761904762, "max_line_length": 77, "alphanum_fraction": 0.4493545184, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7553471637085468}} {"text": "// Copyright Paul A. Bristow 2014, 2015.\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Note that this file contains Quickbook mark-up as well as code\n// and comments, don't change any of the special comment mark-ups!\n\n// Example of finding nth root using 1st and 2nd derivatives of x^n.\n\n#include \n//using boost::math::policies::policy;\n//using boost::math::tools::newton_raphson_iterate;\n//using boost::math::tools::halley_iterate;\n//using boost::math::tools::eps_tolerance; // Binary functor for specified number of bits.\n//using boost::math::tools::bracket_and_solve_root;\n//using boost::math::tools::toms748_solve;\n\n#include \n#include \n#include \n#include \n\n#include // For cpp_dec_float_50.\n#include // using boost::multiprecision::cpp_bin_float_50;\n#ifndef _MSC_VER // float128 is not yet supported by Microsoft compiler at 2013.\n# include \n#endif\n\n#include \n// using std::cout; using std::endl;\n#include \n// using std::setw; using std::setprecision;\n#include \nusing std::numeric_limits;\n#include \n#include // pair, make_pair\n\n\n//[root_finding_nth_functor_2deriv\ntemplate \nstruct nth_functor_2deriv\n{ // Functor returning both 1st and 2nd derivatives.\n BOOST_STATIC_ASSERT_MSG(boost::is_integral::value == false, \"Only floating-point type types can be used!\");\n BOOST_STATIC_ASSERT_MSG((N > 0) == true, \"root N must be > 0!\");\n\n nth_functor_2deriv(T const& to_find_root_of) : a(to_find_root_of)\n { /* Constructor stores value a to find root of, for example: */ }\n\n // using boost::math::tuple; // to return three values.\n std::tuple operator()(T const& x)\n {\n // Return f(x), f'(x) and f''(x).\n using boost::math::pow;\n T fx = pow(x) - a; // Difference (estimate x^n - a).\n T dx = N * pow(x); // 1st derivative f'(x).\n T d2x = N * (N - 1) * pow(x); // 2nd derivative f''(x).\n\n return std::make_tuple(fx, dx, d2x); // 'return' fx, dx and d2x.\n }\nprivate:\n T a; // to be 'nth_rooted'.\n};\n\n//] [/root_finding_nth_functor_2deriv]\n\n/*\nTo show the progress, one might use this before the return statement above?\n#ifdef BOOST_MATH_ROOT_DIAGNOSTIC\nstd::cout << \" x = \" << x << \", fx = \" << fx << \", dx = \" << dx << \", dx2 = \" << d2x << std::endl;\n#endif\n*/\n\n// If T is a floating-point type, might be quicker to compute the guess using a built-in type,\n// probably quickest using double, but perhaps with float or long double, T.\n\n// If T is a type for which frexp and ldexp are not defined,\n// then it is necessary to compute the guess using a built-in type,\n// probably quickest (but limited range) using double,\n// but perhaps with float or long double, or a multiprecision T for the full range of T.\n// typedef double guess_type; is used to specify the this.\n\n//[root_finding_nth_function_2deriv\n\ntemplate \nT nth_2deriv(T x)\n{ // return nth root of x using 1st and 2nd derivatives and Halley.\n\n using namespace std; // Help ADL of std functions.\n using namespace boost::math::tools; // For halley_iterate.\n\n BOOST_STATIC_ASSERT_MSG(boost::is_integral::value == false, \"Only floating-point type types can be used!\");\n BOOST_STATIC_ASSERT_MSG((N > 0) == true, \"root N must be > 0!\");\n BOOST_STATIC_ASSERT_MSG((N > 1000) == false, \"root N is too big!\");\n\n typedef double guess_type; // double may restrict (exponent) range for a multiprecision T?\n\n int exponent;\n frexp(static_cast(x), &exponent); // Get exponent of z (ignore mantissa).\n T guess = ldexp(static_cast(1.), exponent / N); // Rough guess is to divide the exponent by n.\n T min = ldexp(static_cast(1.) / 2, exponent / N); // Minimum possible value is half our guess.\n T max = ldexp(static_cast(2.), exponent / N); // Maximum possible value is twice our guess.\n\n int digits = std::numeric_limits::digits * 0.4; // Accuracy triples with each step, so stop when\n // slightly more than one third of the digits are correct.\n const boost::uintmax_t maxit = 20;\n boost::uintmax_t it = maxit;\n T result = halley_iterate(nth_functor_2deriv(x), guess, min, max, digits, it);\n return result;\n}\n\n//] [/root_finding_nth_function_2deriv]\n\n\ntemplate \nT show_nth_root(T value)\n{ // Demonstrate by printing the nth root using all possibly significant digits.\n //std::cout.precision(std::numeric_limits::max_digits10);\n // or use cout.precision(max_digits10 = 2 + std::numeric_limits::digits * 3010/10000);\n // Or guaranteed significant digits:\n std::cout.precision(std::numeric_limits::digits10);\n\n T r = nth_2deriv(value);\n std::cout << \"Type \" << typeid(T).name() << \" value = \" << value << \", \" << N << \"th root = \" << r << std::endl;\n return r;\n} // print_nth_root\n\n\nint main()\n{\n std::cout << \"nth Root finding Example.\" << std::endl;\n using boost::multiprecision::cpp_dec_float_50; // decimal.\n using boost::multiprecision::cpp_bin_float_50; // binary.\n#ifndef _MSC_VER // Not supported by Microsoft compiler.\n using boost::multiprecision::float128; // Requires libquadmath\n#endif\n try\n { // Always use try'n'catch blocks with Boost.Math to get any error messages.\n\n//[root_finding_n_example_1\n double r1 = nth_2deriv<5, double>(2); // Integral value converted to double.\n\n // double r2 = nth_2deriv<5>(2); // Only floating-point type types can be used!\n\n//] [/root_finding_n_example_1\n\n //show_nth_root<5, float>(2); // Integral value converted to float.\n //show_nth_root<5, float>(2.F); // 'initializing' : conversion from 'double' to 'float', possible loss of data\n\n//[root_finding_n_example_2\n\n\n show_nth_root<5, double>(2.);\n show_nth_root<5, long double>(2.);\n#ifndef _MSC_VER // float128 is not supported by Microsoft compiler 2013.\n show_nth_root<5, float128>(2);\n#endif\n show_nth_root<5, cpp_dec_float_50>(2); // dec\n show_nth_root<5, cpp_bin_float_50>(2); // bin\n//] [/root_finding_n_example_2\n\n // show_nth_root<1000000>(2.); // Type double value = 2, 555th root = 1.00124969405651\n // Type double value = 2, 1000th root = 1.00069338746258\n // Type double value = 2, 1000000th root = 1.00000069314783\n }\n catch (const std::exception& e)\n { // Always useful to include try & catch blocks because default policies\n // are to throw exceptions on arguments that cause errors like underflow, overflow.\n // Lacking try & catch blocks, the program will abort without a message below,\n // which may give some helpful clues as to the cause of the exception.\n std::cout <<\n \"\\n\"\"Message from thrown exception was:\\n \" << e.what() << std::endl;\n }\n return 0;\n} // int main()\n\n\n/*\n//[root_finding_example_output_1\n Using MSVC 2013\n\nnth Root finding Example.\nType double value = 2, 5th root = 1.14869835499704\nType long double value = 2, 5th root = 1.14869835499704\nType class boost::multiprecision::number,1> value = 2,\n 5th root = 1.1486983549970350067986269467779275894438508890978\nType class boost::multiprecision::number,0> value = 2,\n 5th root = 1.1486983549970350067986269467779275894438508890978\n\n//] [/root_finding_example_output_1]\n\n//[root_finding_example_output_2\n\n Using GCC 4.91 (includes float_128 type)\n\n nth Root finding Example.\nType d value = 2, 5th root = 1.14869835499704\nType e value = 2, 5th root = 1.14869835499703501\nType N5boost14multiprecision6numberINS0_8backends16float128_backendELNS0_26expression_template_optionE0EEE value = 2, 5th root = 1.148698354997035006798626946777928\nType N5boost14multiprecision6numberINS0_8backends13cpp_dec_floatILj50EivEELNS0_26expression_template_optionE1EEE value = 2, 5th root = 1.1486983549970350067986269467779275894438508890978\nType N5boost14multiprecision6numberINS0_8backends13cpp_bin_floatILj50ELNS2_15digit_base_typeE10EviLi0ELi0EEELNS0_26expression_template_optionE0EEE value = 2, 5th root = 1.1486983549970350067986269467779275894438508890978\n\nRUN SUCCESSFUL (total time: 63ms)\n\n//] [/root_finding_example_output_2]\n*/\n\n/*\nThrow out of range using GCC release mode :-(\n\n */\n", "meta": {"hexsha": "c83e574a15514529e8f380900c50fb856dd6fadc", "size": 8801, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/root_finding_n_example.cpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/root_finding_n_example.cpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/root_finding_n_example.cpp", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 41.1261682243, "max_line_length": 220, "alphanum_fraction": 0.7096920804, "num_tokens": 2501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7551084335212301}} {"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union’s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include \n#include \n#include \n#include \n\nnamespace fluid {\nnamespace algorithm {\n\nclass PCA\n{\npublic:\n using MatrixXd = Eigen::MatrixXd;\n using VectorXd = Eigen::VectorXd;\n\n void init(RealMatrixView in)\n {\n using namespace Eigen;\n using namespace _impl;\n MatrixXd input = asEigen(in);\n mMean = input.colwise().mean();\n MatrixXd X = (input.rowwise() - mMean.transpose());\n BDCSVD svd(X.matrix(), ComputeThinV | ComputeThinU);\n mBases = svd.matrixV();\n mValues = svd.singularValues();\n mInitialized = true;\n }\n\n void init(RealMatrixView bases, RealVectorView values, RealVectorView mean)\n {\n mBases = _impl::asEigen(bases);\n mValues = _impl::asEigen(values);\n mMean = _impl::asEigen(mean);\n mInitialized = true;\n }\n\n void processFrame(const RealVectorView in, RealVectorView out, index k) const\n {\n using namespace Eigen;\n using namespace _impl;\n if (k > mBases.cols()) return;\n VectorXd input = asEigen(in);\n input = input - mMean;\n VectorXd result = input.transpose() * mBases.block(0, 0, mBases.rows(), k);\n out = _impl::asFluid(result);\n }\n\n double process(const RealMatrixView in, RealMatrixView out, index k) const\n {\n using namespace Eigen;\n using namespace _impl;\n if (k > mBases.cols()) return 0;\n MatrixXd input = asEigen(in);\n MatrixXd result = (input.rowwise() - mMean.transpose()) *\n mBases.block(0, 0, mBases.rows(), k);\n double variance = 0;\n double total = mValues.sum();\n for (index i = 0; i < k; i++) variance += mValues[i];\n out = _impl::asFluid(result);\n return variance / total;\n }\n\n bool initialized() const { return mInitialized; }\n void getBases(RealMatrixView out) const { out = _impl::asFluid(mBases); }\n void getValues(RealVectorView out) const { out = _impl::asFluid(mValues); }\n void getMean(RealVectorView out) const { out = _impl::asFluid(mMean); }\n index dims() const { return mBases.rows(); }\n index size() const { return mBases.cols(); }\n void clear()\n {\n mBases.setZero();\n mMean.setZero();\n mInitialized = false;\n }\n\n MatrixXd mBases;\n VectorXd mValues;\n VectorXd mMean;\n bool mInitialized{false};\n};\n}; // namespace algorithm\n}; // namespace fluid\n", "meta": {"hexsha": "2ff4d4714935e052260b78f4ace5d855a49e7ce0", "size": 2868, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/PCA.hpp", "max_stars_repo_name": "chriskiefer/flucoma-core", "max_stars_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T15:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:51:36.000Z", "max_issues_repo_path": "include/algorithms/public/PCA.hpp", "max_issues_repo_name": "chriskiefer/flucoma-core", "max_issues_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2020-05-13T20:25:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T18:05:35.000Z", "max_forks_repo_path": "include/algorithms/public/PCA.hpp", "max_forks_repo_name": "chriskiefer/flucoma-core", "max_forks_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-05-11T15:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T12:15:36.000Z", "avg_line_length": 29.875, "max_line_length": 79, "alphanum_fraction": 0.6788702929, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9678992969868542, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7549545798106875}} {"text": "#pragma once\r\n\r\n#include \r\n\r\n#include \r\n#include \r\n\r\nnamespace skynet{ namespace statistics{\r\n\t\r\n\r\n\tstruct pca_result{\r\n\t\tEigen::MatrixXd eigen_vectors;\r\n\t\tEigen::VectorXd eigen_values;\r\n\t\tEigen::VectorXd mean;\r\n\t};\r\n\r\n\t//mxn matrix warning: m is the num of samples\r\n\tpca_result pca(const Eigen::MatrixXd &mat){\r\n\t\tEigen::VectorXd mean(mat.rows());\r\n\t\tfor (int row = 0; row < mat.rows(); ++row){\r\n\t\t\tdouble temp = 0;\r\n\t\t\tfor (int col = 0; col < mat.cols(); ++col){\r\n\t\t\t\ttemp += mat(row, col);\r\n\t\t\t}\r\n\t\t\ttemp /= mat.cols();\r\n\t\t\tmean(row) = temp;\r\n\t\t}\r\n\r\n\t\tEigen::MatrixXd data(mat.rows(), mat.cols());\r\n\t\tfor (int row = 0; row < mat.rows(); ++row){\r\n\t\t\tfor (int col = 0; col < mat.cols(); ++col){\r\n\t\t\t\tdata(row, col) = mat(row, col) - mean(row);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//auto data_t = data.transpose() / sqrt(mat.rows());\r\n\t\tEigen::JacobiSVD svd(data, Eigen::ComputeFullU | Eigen::ComputeFullV);\r\n\t\tpca_result pca;\r\n\t\tpca.eigen_values = move(svd.singularValues().cwiseAbs2());\r\n\t\tpca.eigen_vectors = move(svd.matrixU());\r\n\t\tpca.mean = mean;\r\n\t\t\r\n\t\treturn pca;\r\n\t//\tauto sample_size = mat.row\r\n\t}\r\n\r\n}}\r\n", "meta": {"hexsha": "c64294218bc0847cdc32fbe06bdf19ea29583728", "size": 1169, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "skynet/statistics/pca.hpp", "max_stars_repo_name": "zhangzhimin/skynet", "max_stars_repo_head_hexsha": "a311b86433821a071002dd279d57333baba1f973", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-08-02T03:10:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-16T01:07:55.000Z", "max_issues_repo_path": "skynet/statistics/pca.hpp", "max_issues_repo_name": "zhangzhimin/skynet", "max_issues_repo_head_hexsha": "a311b86433821a071002dd279d57333baba1f973", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "skynet/statistics/pca.hpp", "max_forks_repo_name": "zhangzhimin/skynet", "max_forks_repo_head_hexsha": "a311b86433821a071002dd279d57333baba1f973", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3541666667, "max_line_length": 91, "alphanum_fraction": 0.5979469632, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7549137805581876}} {"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n\n This is an example illustrating the use the general purpose non-linear \n least squares optimization routines from the dlib C++ Library.\n\n This example program will demonstrate how these routines can be used for data fitting.\n In particular, we will generate a set of data and then use the least squares \n routines to infer the parameters of the model which generated the data.\n*/\n\n\n#include \n#include \n#include \n\n\nusing namespace std;\nusing namespace dlib;\n\n// ----------------------------------------------------------------------------------------\n\ntypedef matrix input_vector;\ntypedef matrix parameter_vector;\n\n// ----------------------------------------------------------------------------------------\n\n// We will use this function to generate data. It represents a function of 2 variables\n// and 3 parameters. The least squares procedure will be used to infer the values of \n// the 3 parameters based on a set of input/output pairs.\ndouble model (\n const input_vector& input,\n const parameter_vector& params\n)\n{\n const double p0 = params(0);\n const double p1 = params(1);\n const double p2 = params(2);\n\n const double i0 = input(0);\n const double i1 = input(1);\n\n const double temp = p0*i0 + p1*i1 + p2;\n\n return temp*temp;\n}\n\n// ----------------------------------------------------------------------------------------\n\n// This function is the \"residual\" for a least squares problem. It takes an input/output\n// pair and compares it to the output of our model and returns the amount of error. The idea\n// is to find the set of parameters which makes the residual small on all the data pairs.\ndouble residual (\n const std::pair& data,\n const parameter_vector& params\n)\n{\n return model(data.first, params) - data.second;\n}\n\n// ----------------------------------------------------------------------------------------\n\n// This function is the derivative of the residual() function with respect to the parameters.\nparameter_vector residual_derivative (\n const std::pair& data,\n const parameter_vector& params\n)\n{\n parameter_vector der;\n\n const double p0 = params(0);\n const double p1 = params(1);\n const double p2 = params(2);\n\n const double i0 = data.first(0);\n const double i1 = data.first(1);\n\n const double temp = p0*i0 + p1*i1 + p2;\n\n der(0) = i0*2*temp;\n der(1) = i1*2*temp;\n der(2) = 2*temp;\n\n return der;\n}\n\n// ----------------------------------------------------------------------------------------\n\n\n\n#if defined(BUILD_MONOLITHIC)\n#define main(cnt, arr) dlib_least_squares_ex_main(cnt, arr)\n#endif\n\nint main(int argc, const char** argv)\n{\n try\n {\n // randomly pick a set of parameters to use in this example\n const parameter_vector params = 10*randm(3,1);\n cout << \"params: \" << trans(params) << endl;\n\n\n // Now let's generate a bunch of input/output pairs according to our model.\n std::vector > data_samples;\n input_vector input;\n for (int i = 0; i < 1000; ++i)\n {\n input = 10*randm(2,1);\n const double output = model(input, params);\n\n // save the pair\n data_samples.push_back(make_pair(input, output));\n }\n\n // Before we do anything, let's make sure that our derivative function defined above matches\n // the approximate derivative computed using central differences (via derivative()). \n // If this value is big then it means we probably typed the derivative function incorrectly.\n cout << \"derivative error: \" << length(residual_derivative(data_samples[0], params) - \n derivative(residual)(data_samples[0], params) ) << endl;\n\n\n\n\n\n // Now let's use the solve_least_squares_lm() routine to figure out what the\n // parameters are based on just the data_samples.\n parameter_vector x;\n x = 1;\n\n cout << \"Use Levenberg-Marquardt\" << endl;\n // Use the Levenberg-Marquardt method to determine the parameters which\n // minimize the sum of all squared residuals.\n solve_least_squares_lm(objective_delta_stop_strategy(1e-7).be_verbose(), \n residual,\n residual_derivative,\n data_samples,\n x);\n\n // Now x contains the solution. If everything worked it will be equal to params.\n cout << \"inferred parameters: \"<< trans(x) << endl;\n cout << \"solution error: \"<< length(x - params) << endl;\n cout << endl;\n\n\n\n\n x = 1;\n cout << \"Use Levenberg-Marquardt, approximate derivatives\" << endl;\n // If we didn't create the residual_derivative function then we could\n // have used this method which numerically approximates the derivatives for you.\n solve_least_squares_lm(objective_delta_stop_strategy(1e-7).be_verbose(), \n residual,\n derivative(residual),\n data_samples,\n x);\n\n // Now x contains the solution. If everything worked it will be equal to params.\n cout << \"inferred parameters: \"<< trans(x) << endl;\n cout << \"solution error: \"<< length(x - params) << endl;\n cout << endl;\n\n\n\n\n x = 1;\n cout << \"Use Levenberg-Marquardt/quasi-newton hybrid\" << endl;\n // This version of the solver uses a method which is appropriate for problems\n // where the residuals don't go to zero at the solution. So in these cases\n // it may provide a better answer.\n solve_least_squares(objective_delta_stop_strategy(1e-7).be_verbose(), \n residual,\n residual_derivative,\n data_samples,\n x);\n\n // Now x contains the solution. If everything worked it will be equal to params.\n cout << \"inferred parameters: \"<< trans(x) << endl;\n cout << \"solution error: \"<< length(x - params) << endl;\n\n }\n catch (std::exception& e)\n {\n cout << e.what() << endl;\n }\n}\n\n// Example output:\n/*\nparams: 8.40188 3.94383 7.83099 \n\nderivative error: 9.78267e-06\nUse Levenberg-Marquardt\niteration: 0 objective: 2.14455e+10\niteration: 1 objective: 1.96248e+10\niteration: 2 objective: 1.39172e+10\niteration: 3 objective: 1.57036e+09\niteration: 4 objective: 2.66917e+07\niteration: 5 objective: 4741.9\niteration: 6 objective: 0.000238674\niteration: 7 objective: 7.8815e-19\niteration: 8 objective: 0\ninferred parameters: 8.40188 3.94383 7.83099 \n\nsolution error: 0\n\nUse Levenberg-Marquardt, approximate derivatives\niteration: 0 objective: 2.14455e+10\niteration: 1 objective: 1.96248e+10\niteration: 2 objective: 1.39172e+10\niteration: 3 objective: 1.57036e+09\niteration: 4 objective: 2.66917e+07\niteration: 5 objective: 4741.87\niteration: 6 objective: 0.000238701\niteration: 7 objective: 1.0571e-18\niteration: 8 objective: 4.12469e-22\ninferred parameters: 8.40188 3.94383 7.83099 \n\nsolution error: 5.34754e-15\n\nUse Levenberg-Marquardt/quasi-newton hybrid\niteration: 0 objective: 2.14455e+10\niteration: 1 objective: 1.96248e+10\niteration: 2 objective: 1.3917e+10\niteration: 3 objective: 1.5572e+09\niteration: 4 objective: 2.74139e+07\niteration: 5 objective: 5135.98\niteration: 6 objective: 0.000285539\niteration: 7 objective: 1.15441e-18\niteration: 8 objective: 3.38834e-23\ninferred parameters: 8.40188 3.94383 7.83099 \n\nsolution error: 1.77636e-15\n*/\n", "meta": {"hexsha": "2851feb02cf89aee8fe9346dc336795a840427af", "size": 7888, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/least_squares_ex.cpp", "max_stars_repo_name": "GerHobbelt/dlib", "max_stars_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/least_squares_ex.cpp", "max_issues_repo_name": "GerHobbelt/dlib", "max_issues_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/least_squares_ex.cpp", "max_forks_repo_name": "GerHobbelt/dlib", "max_forks_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5659574468, "max_line_length": 103, "alphanum_fraction": 0.6044624746, "num_tokens": 1933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8670357649558007, "lm_q1q2_score": 0.7548389685828738}} {"text": "/******************************************************************************\n Prácticas de cálculo matricial de estructuras\n https://github.com/ingmec-ual/practicas-calculo-matricial-estructuras\n\n Copyright 2017 - Jose Luis Blanco Claraco \n University of Almeria\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n 1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n 3. Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n Complete BSD-3-clause License: https://opensource.org/licenses/BSD-3-Clause\n******************************************************************************/\n\n#include // Libreria Eigen (matrices)\n#include \"eigen_indexing.h\" // Funcion indexing(MAT, idxs_rows, idxs_cols)\n#include // Para std::cout\n\nint main()\n{\n\tEigen::Matrix3d M = Eigen::Matrix3d::Identity();\n\tstd::cout << \"Matriz identidad I_3:\" << std::endl << M << std::endl;\n\n\t// Modificamos la matriz:\n\tfor (int i = 0; i < 3; i++) {\n\t\tfor (int j = 0; j < 3; j++) {\n\t\t\tM(i, j) += i+j;\n\t\t}\n\t}\n\n\tstd::cout << \"Matriz M:\" << std::endl << M << std::endl;\n\tstd::cout << \"Inversa de la matriz M:\" << std::endl << M.inverse() << std::endl;\n\n\treturn 0; // el programa finaliza sin errores\n}\n", "meta": {"hexsha": "bd954a0614c4fa99f4eea9d72aa2731f67e50446", "size": 1759, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ejemplo_cpp.cpp", "max_stars_repo_name": "ingmec-ual/practica1-calculo-matricial-estructuras", "max_stars_repo_head_hexsha": "1740f098d25dd306a9eeb69978888d58af46c9b7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T13:20:22.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-09T13:20:22.000Z", "max_issues_repo_path": "ejemplo_cpp.cpp", "max_issues_repo_name": "ingmec-ual/practicas-calculo-matricial-estructuras", "max_issues_repo_head_hexsha": "1740f098d25dd306a9eeb69978888d58af46c9b7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ejemplo_cpp.cpp", "max_forks_repo_name": "ingmec-ual/practicas-calculo-matricial-estructuras", "max_forks_repo_head_hexsha": "1740f098d25dd306a9eeb69978888d58af46c9b7", "max_forks_repo_licenses": ["BSD-3-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.880952381, "max_line_length": 81, "alphanum_fraction": 0.6498010233, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.8670357615200475, "lm_q1q2_score": 0.7548389597696403}} {"text": "#pragma once\n\n#include \n#include \n\nclass KalmanFilter {\n\npublic:\n\n // Generate the Kalman Filter with specified matrices\n // A : System dynamics matrix\n // B : Input matrix\n // C : Output matrix\n // Q : Process noise covariance\n // R : Measurement noise covariance\n // P0 : Initial error covariance\n KalmanFilter(\n const Eigen::MatrixXd& A,\n const Eigen::MatrixXd& B,\n const Eigen::MatrixXd& C,\n const Eigen::MatrixXd& Q,\n const Eigen::MatrixXd& R,\n const Eigen::MatrixXd& P0);\n\n // Initialize the filter with a guess for the initial states\n void init(const Eigen::VectorXd& x0);\n\n // Update the a-priori estimates based on the system model and control input\n void prediction_update(const Eigen::VectorXd& u);\n\n // Update the a-posteriori estimates based on the measurements\n void innovation_update(const Eigen::VectorXd& y);\n\n // Return the current state\n Eigen::VectorXd get_state() {return x_hat_post;};\n\n // Return the current state error covariance\n Eigen::MatrixXd get_P() {return P_post;}; \n\nprivate:\n // Matrices used in predict and correction steps\n Eigen::MatrixXd A, B, C, Q, R, P_prio, P_post, K;\n\n // system dimensions\n // n : # state variables to be estimated\n // m : # measured variables\n // c : # control input variables\n int32_t m, n, c;\n\n // n-sized identity\n Eigen::MatrixXd I;\n\n // is the filter initialized?\n bool initialized = false;\n\n // Estimated states\n Eigen::VectorXd x_hat_prio, x_hat_post;\n\n};\n", "meta": {"hexsha": "e37adcc19936a094b04cc90a494c190a05fa1b4f", "size": 1560, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "KalmanFilter/kalman.hpp", "max_stars_repo_name": "goksanisil23/lazy_minimal_robotics", "max_stars_repo_head_hexsha": "ee98a05ffbddfa62e7bb228ca121d0620874a271", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "KalmanFilter/kalman.hpp", "max_issues_repo_name": "goksanisil23/lazy_minimal_robotics", "max_issues_repo_head_hexsha": "ee98a05ffbddfa62e7bb228ca121d0620874a271", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "KalmanFilter/kalman.hpp", "max_forks_repo_name": "goksanisil23/lazy_minimal_robotics", "max_forks_repo_head_hexsha": "ee98a05ffbddfa62e7bb228ca121d0620874a271", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0, "max_line_length": 80, "alphanum_fraction": 0.6653846154, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850021922959, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7543013401958739}} {"text": "#include \n using boost::math::binomial;\n#include \n#include // for normal_distribution\n using boost::math::normal; // typedef provides default type is double.\n\n#include \nusing boost::math::hypergeometric; \n\n#include \n#include \n#include \"container.h\"\n#include \"stat.h\"\n \n using namespace std;\n \ndouble p_value_for_z_score(double z)\n\t{\n\t\tnormal s;\n\t\treturn cdf(s, -fabs(z));\n\t} \n\n// note both enrichment and depletion\ndouble binom_test(int trials,int success,double success_fraction)\n{\n binomial binom(trials, success_fraction);\n double p = 1.0 - cdf(binom,success);\n if (p > 0.5) p = 1.0 - p; //depletion\n return p;\n}\n\ndouble hypergeometric_test(unsigned k, unsigned r, unsigned n, unsigned N)\n{\t// k: positive samples\n\t// n: total samples\n\t// r: total positive\n\t// N: total \n\thypergeometric hg(r,n,N);\n\tdouble p = 1.0 - cdf(hg,k);\n\treturn p;\n}\n\n// normal approximation is ok for n1 and n2 > 8\n// see paper: Carine A. Bellera et al, Normal Approximations to the Distributions of the Wilcoxon\n// Statistics: Accurate to What N? Graphical Insights, Journal of Statistics Education, Volume 18, Number 2, (2010)\n// http://www.amstat.org/publications/jse/v18n2/bellera.pdf\narray Mann_Whitney_U_test(vector ranks, int N)\n{\n\tdouble n1 = ranks.size();\n\tdouble n2 = N - n1;\n\tdouble rank_sum = ranks[0];\n\tfor (int i=1;i res = {{z,p}};\n\treturn res;\n}\n\n\narray two_samples_t_test_equal_sd(double Sm1,double Sd1, unsigned Sn1, double Sm2, double Sd2,unsigned Sn2)\n{\n //\n // Sm1 = Sample Mean 1.\n // Sd1 = Sample Standard Deviation 1.\n // Sn1 = Sample Size 1.\n // Sm2 = Sample Mean 2.\n // Sd2 = Sample Standard Deviation 2.\n // Sn2 = Sample Size 2.\n //\n // A Students t test applied to two sets of data.\n // We are testing the null hypothesis that the two\n // samples have the same mean and that any difference\n // if due to chance.\n // See http://www.itl.nist.gov/div898/handbook/eda/section3/eda353.htm\n //\n using namespace std;\n using namespace boost::math;\n\n // Now we can calculate and output some stats:\n //\n // Degrees of freedom:\n double v = Sn1 + Sn2 - 2;\n // Pooled variance:\n double sp = sqrt(((Sn1-1) * Sd1 * Sd1 + (Sn2-1) * Sd2 * Sd2) / v);\n // t-statistic:\n double t_stat = (Sm1 - Sm2) / (sp * sqrt(1.0 / Sn1 + 1.0 / Sn2));\n //\n // Define our distribution, and get the probability:\n //\n students_t dist(v);\n double q = cdf(complement(dist, fabs(t_stat)));\n\n\tarray res = {{t_stat,q}};\n\n\treturn res;\n}\n\narray two_samples_t_test_unequal_sd(double Sm1,double Sd1, unsigned Sn1,double Sm2, double Sd2,unsigned Sn2)\n{\n //\n // Sm1 = Sample Mean 1.\n // Sd1 = Sample Standard Deviation 1.\n // Sn1 = Sample Size 1.\n // Sm2 = Sample Mean 2.\n // Sd2 = Sample Standard Deviation 2.\n // Sn2 = Sample Size 2.\n // alpha = Significance Level.\n //\n // A Students t test applied to two sets of data.\n // We are testing the null hypothesis that the two\n // samples have the same mean and that any difference\n // if due to chance.\n // See http://www.itl.nist.gov/div898/handbook/eda/section3/eda353.htm\n //\n using namespace std;\n using namespace boost::math;\n\n //\n // Degrees of freedom:\n double v = Sd1 * Sd1 / Sn1 + Sd2 * Sd2 / Sn2;\n v *= v;\n double t1 = Sd1 * Sd1 / Sn1;\n t1 *= t1;\n t1 /= (Sn1 - 1);\n double t2 = Sd2 * Sd2 / Sn2;\n t2 *= t2;\n t2 /= (Sn2 - 1);\n v /= (t1 + t2);\n // t-statistic:\n double t_stat = (Sm1 - Sm2) / sqrt(Sd1 * Sd1 / Sn1 + Sd2 * Sd2 / Sn2);\n //\n // Define our distribution, and get the probability:\n //\n students_t dist(v);\n double q = cdf(complement(dist, fabs(t_stat)));\n\n\tarray res = {{t_stat,q}};\n\treturn res;\n}\n\n// return 6 double\n// t.statistics, p-value, Sm1, Sd1, Sm2, Sd2\narray t_test(vector x, vector y, bool equal_var)\n{\n\tunsigned Sn1 = x.size();\n\tdouble Sm1 = mean(x);\n\tdouble Sd1 = sqrt(var(x));\n\n unsigned Sn2 = y.size();\n double Sm2 = mean(y); \n double Sd2 = sqrt(var(y)); \n\t\n\t//debug \n\t//cout << Sn1 << \",\" << Sm1 << \",\" << Sd1 << endl;\n\t//cout << Sn2 << \",\" << Sm2 << \",\" << Sd2 << endl;\t\n\n\tarray res = {{-1,-1,Sm1, Sd1, Sm2, Sd2}};\n\t\n\tarray ttest;\n\tif (equal_var) ttest = two_samples_t_test_equal_sd(Sm1,Sd1,Sn1,Sm2,Sd2,Sn2);\n\telse ttest = two_samples_t_test_unequal_sd(Sm1,Sd1,Sn1,Sm2,Sd2,Sn2);\t\n\n\tres[0] = ttest[0];\n\tres[1] = ttest[1];\n\t\n\treturn res;\n}\n", "meta": {"hexsha": "9b14ddfab0d0961c11b4d9b6bf40fef7a880576c", "size": 5080, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/stat.cpp", "max_stars_repo_name": "xuebingwu/PKA", "max_stars_repo_head_hexsha": "45f8d808cc36879d5da91213bc9902cd45f86b07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-01-26T15:50:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-01T08:27:00.000Z", "max_issues_repo_path": "src/stat.cpp", "max_issues_repo_name": "xuebingwu/PKA", "max_issues_repo_head_hexsha": "45f8d808cc36879d5da91213bc9902cd45f86b07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-07-18T21:17:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-17T02:54:52.000Z", "max_forks_repo_path": "src/stat.cpp", "max_forks_repo_name": "xuebingwu/PKA", "max_forks_repo_head_hexsha": "45f8d808cc36879d5da91213bc9902cd45f86b07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-05-13T08:01:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-07T14:10:57.000Z", "avg_line_length": 29.3641618497, "max_line_length": 151, "alphanum_fraction": 0.6411417323, "num_tokens": 1673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591979, "lm_q2_score": 0.7981867801399694, "lm_q1q2_score": 0.7542822824768947}} {"text": "// intersections.cpp\n//\n// Copyright (c) 2018\n// Justinas V. Daugmaudis\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//[intersections\n/*`\n For the source of this example see\n [@boost://libs/random/example/intersections.cpp intersections.cpp].\n\n This example demonstrates generating quasi-randomly distributed chord\n entry and exit points on an S[sup 2] sphere.\n\n First we include the headers we need for __niederreiter_base2\n and __uniform_01 distribution.\n */\n\n#include \n#include \n\n#include \n\n#include \n\n/*`\n We use 4-dimensional __niederreiter_base2 as a source of randomness.\n */\nboost::random::niederreiter_base2 gen(4);\n\n\nint main()\n{\n typedef boost::tuple point_t;\n\n const std::size_t n_points = 100; // we will generate 100 points\n\n std::vector points;\n points.reserve(n_points);\n\n /*<< __niederreiter_base2 produces integers in the range [0, 2[sup 64]-1].\n However, we want numbers in the range [0, 1). The distribution\n __uniform_01 performs this transformation.\n >>*/\n boost::random::uniform_01 dist;\n\n for (std::size_t i = 0; i != n_points; ++i)\n {\n /*`\n Using formula from J. Rovira et al., \"Point sampling with uniformly distributed lines\", 2005\n to compute uniformly distributed chord entry and exit points on the surface of a sphere.\n */\n double cos_theta = 1 - 2 * dist(gen);\n double sin_theta = std::sqrt(1 - cos_theta * cos_theta);\n double phi = boost::math::constants::two_pi() * dist(gen);\n double sin_phi = std::sin(phi), cos_phi = std::cos(phi);\n\n point_t point_on_sphere(sin_theta*sin_phi, cos_theta, sin_theta*cos_phi);\n\n /*`\n Here we assume that our sphere is a unit sphere at origin. If your sphere was\n different then now would be the time to scale and translate the `point_on_sphere`.\n */\n\n points.push_back(point_on_sphere);\n }\n\n /*`\n Vector `points` now holds generated 3D points on a sphere.\n */\n\n return 0;\n}\n\n//]\n", "meta": {"hexsha": "fea40d6a4a9c05d061db296922c880ac25c549e7", "size": 2222, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/random/example/intersections.cpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/libs/random/example/intersections.cpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/libs/random/example/intersections.cpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 28.1265822785, "max_line_length": 98, "alphanum_fraction": 0.703420342, "num_tokens": 583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672954, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7542572353439843}} {"text": "/*\n * oper_matrix.cpp\n *\n * Created on: 2017. 6. 6.\n * Author: cho\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nnamespace ublas = boost::numeric::ublas;\n\n/// number of data\nconst unsigned int N = 15;\nconst int order = 3; // 3 means second order polynomial\n\n// return polynomial value\n// ex, return y = a0 + a1*x + a2*x^2\ndouble polyval( const ublas::vector& a, const double x ) {\n\tublas::vector tmp(a);\n\n\tfor ( unsigned i = 1; i < a.size(); ++i ) {\n\t\tfor ( unsigned j = i; j < a.size(); ++j )\n\t\t\ttmp(j) *= x;\n\t}\n\n\treturn ublas::sum( tmp );\n}\n\nint main() {\n\tcout << \"==== START \" << endl;\n\trandom_device rd; // seed, rd()\n\tmt19937_64 gen(rd()); // random number generator\n\n\tublas::vector t (N); // time vector, sec\n\tfor (unsigned i = 0; i < t.size(); ++i) t(i) = (i+1);\n\tcout << \"t(\"< dis_y( -10, 10 );\n\tublas::vector y (N); // measured value\n\tfor (unsigned i = 0; i < y.size(); ++i) y(i) = dis_y(gen);\n\tcout << \"y(\"< X(N, order); // X = Vandermonde matrix\n\tublas::column(X, 0) = ublas::vector(N, 1); // 0 column = t^0, all one\n\tublas::column(X, 1) = t; // 1 column = t^1, t itself\n//\tublas::column(X, 2) = ublas::element_prod(t, t); // 2 column = t^2\n\tfor ( unsigned j = 2; j M = prod( trans(X), X );\n\tcout << \"M = trans(X) x X = \" << M << endl;\n\n\tublas::vector Y = prod( trans(X), y );\n\tcout << \"Y = trans(X) x y = \" << Y << endl;\n\n\tcout << endl;\n\tcout << \"==== solve the equation : M x a = Y by LU factorization\" << endl;\n\tcout << \"==== LU=PM and PM x a = PY\" << endl;\n\tcout << \"==== so, LU x a = PY\" << endl;\n\tublas::permutation_matrix pm(M.size1());\n\tublas::vector a( Y ); // a <- Y\n\tublas::matrix LU( M ); // LU <- M\n\tbool singular = ublas::lu_factorize( LU, pm); // LU <- LU\n\tif ( singular ) {\n\t\tcout << \"ERROR!!! \" << endl;\n\t} else {\n\t\tcout << \"LU = \" << LU << endl;\n\t\tcout << \"Y = \" << Y << endl;\n\t\tcout << \"pm = \" << pm << endl;\n\t\tublas::swap_rows( pm, a); // a <- PY\n\t\tublas::inplace_solve( LU, a, ublas::unit_lower_tag()); // a <- z : Lz = PY\n\t\tublas::inplace_solve( LU, a, ublas::upper_tag()); // a <- x : Ux = z\n\t\tcout << \"polynomial coefficient = \" << a << endl;\n\t\tcout << \"prod( M, a ) = \" << prod( M, a ) << endl;\n\t}\n\n\tcout << endl;\n\tcout << \"==== y = \"<< a(0) << \" + (\" << a(1) << \")*x + (\"<< a(2) << \")*x^2\" << endl;\n\tcout << \"==== y(1) = \" << a(0) + a(1) + a(2);\n\tcout << \", y(2) = \" << a(0) + a(1)*2 + a(2)*2*2;\n\tcout << \", y(3) = \" << a(0) + a(1)*3 + a(2)*3*3 << endl;\n\n\tcout << \"==== run 10 times\" << endl;\n\tfor ( int cnt = 0; cnt < 10; ++ cnt ) {\n\t\tcout << endl;\n\t\tcout << \"[\" << cnt << \"] t = \" << t << endl;\n\n\t\tfor (unsigned i = 0; i < y.size(); ++i) y(i) = dis_y(gen);\n\t\tcout << \"[\" << cnt << \"] y = \" << y << endl;\n\n\t\tublas::vector a( prod( trans(X), y ) ); // a <- trans(X) x y\n\t\tublas::swap_rows( pm, a); // a <- PY\n\t\tublas::inplace_solve( LU, a, ublas::unit_lower_tag()); // a <- z : Lz = PY\n\t\tublas::inplace_solve( LU, a, ublas::upper_tag()); // a <- x : Ux = z\n\t\tcout << \"polynomial coefficient = \" << a << endl;\n\t\tcout << \"[\" << cnt << \"] \";\n\t\tfor ( double x : t ) {\n\t\t\tcout << \"y(\" << x << \") = \" << polyval(a, x) << \", \";\n\t\t}\n\t\tcout << endl;\n\t}\n\n\t// generate data for plot\n\tcout << \"============== plot data ===========\" << endl;\n\tcout << \"t, y, polyval_y\" << endl;\n\tfor ( unsigned i = 0; i < 20; ++i ) {\n\t\ty(0) = dis_y(gen);\n\t\tfor (unsigned i = 1; i < y.size(); ++i) y(i) = y(i-1) + dis_y(gen);\n\t\tublas::vector a( prod( trans(X), y ) );\n\t\tublas::lu_substitute( LU, pm, a );\n\t\tfor ( unsigned j = 0; j < N; ++ j ) {\n\t\t\tcout << t(j) << \",\" << y(j) << \",\" << polyval(a, t(j)) << endl;\n\t\t}\n\t}\n\n\tcout << \"==== END \" << endl;\n}\n", "meta": {"hexsha": "46ee8d812a4a7d3cf15576cc81f5f8637228286d", "size": 4600, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost_ublas/polyfit.cpp", "max_stars_repo_name": "batangr00t/cppLab", "max_stars_repo_head_hexsha": "3946e702692dffb53f92c776e9e8c4a073d68bc9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost_ublas/polyfit.cpp", "max_issues_repo_name": "batangr00t/cppLab", "max_issues_repo_head_hexsha": "3946e702692dffb53f92c776e9e8c4a073d68bc9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost_ublas/polyfit.cpp", "max_forks_repo_name": "batangr00t/cppLab", "max_forks_repo_head_hexsha": "3946e702692dffb53f92c776e9e8c4a073d68bc9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8484848485, "max_line_length": 89, "alphanum_fraction": 0.5004347826, "num_tokens": 1604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7542572212703793}} {"text": "// ***********************************************************************\r\n// Code Created by James Michael Armstrong (https://github.com/BlazesRus)\r\n// Latest Code Release at https://github.com/BlazesRus/BlazesRusSharedCode\r\n// ***********************************************************************\r\n\r\n#include \r\n#include \"MediumDec.hpp\"\r\n\r\nusing MediumDec = BlazesRusCode::MediumDec;\r\nusing VariableConversionFunctions = BlazesRusCode::VariableConversionFunctions;\r\n\r\n#include \r\n#include \"FloatingOperations.hpp\"\r\n\r\n#include \r\n#include \r\n#include \r\n\r\nnamespace BlazesRusDebug\r\n{\r\n /// \r\n /// Get the (n)th Root\r\n /// Code from https://rosettacode.org/wiki/Nth_root#C.23 (Derived from C version)\r\n /// \r\n /// The value to apply the root to.\r\n /// The n value to apply with root.\r\n /// Precision level (smaller = more precise)\r\n /// \r\n static MediumDec NthRootV1(MediumDec value, int n)\r\n {//Accuracy is off for 4th root of 4 compared to calculator at (1.65625 compared to 1.4953487812212205419118989941409)\r\n MediumDec Prec = MediumDec(0, 10);\r\n MediumDec NegPrec = MediumDec(MediumDec::NegativeRep, 10);//-Prec;\r\n double PrecFl = DBL_EPSILON * 10;\r\n double NegPrecFL = -DBL_EPSILON * 10;\r\n \r\n MediumDec d, r = MediumDec::One;\r\n double dFL, rFL = 1.0;\r\n\r\n double valAsFloating = (double)value;\r\n int nMinus1 = n - 1;\r\n\r\n MediumDec powResult;\r\n double powResultFL;\r\n //if (n < 1 || (value < 0.0 && !(n & 1))) {\r\n // return;//0.0 / 0.0; /* NaN */\r\n //}\r\n do {\r\n powResultFL = pow(rFL, nMinus1);\r\n powResult = MediumDec::Pow(r, nMinus1);\r\n dFL = valAsFloating / powResultFL - rFL;\r\n d = value / powResult - r;\r\n dFL /= n;\r\n d /= n;\r\n rFL += dFL;\r\n r += d;\r\n //std::cout << \"PowerResult Values(double,MediumDec) =\" << powResultFL << \",\" << powResult.ToString() << std::endl;\r\n //std::cout << \"Floating Values(d,r) =\" << dFL << \",\" << rFL << std::endl;\r\n //std::cout << \"MediumDec Values(d,r) =\" << d.ToString() << \",\" << r.ToString();\r\n std::cout << std::endl;\r\n } while (d >= PrecFl || d <= NegPrecFL);//while (d >= Prec || d <= NegPrec);//precision check condition\r\n return r;\r\n }\r\n\r\n /// \r\n /// Finds nTh Root of value based on https://stackoverflow.com/questions/9652549/self-made-pow-c code\r\n /// \r\n /// The value.\r\n /// The nth value.\r\n /// Precision level (larger = more precise)\r\n /// MediumDec\r\n static MediumDec NthRootV4(MediumDec value, int n, int KPrecision=5)\r\n {\r\n int nMinus1 = n - 1;\r\n int nPlus1 = n + 1;\r\n const int LastElem = KPrecision-1;\r\n std::vector x;\r\n x.push_back(MediumDec::One);\r\n MediumDec Temp;\r\n for (int XElem = 0; XElem < KPrecision; ++XElem)\r\n {\r\n Temp = (MediumDec::One / n) * (nMinus1 * x.back() + value / MediumDec::PowConstOp(x.back(), nMinus1));\r\n x.push_back(Temp);\r\n }\r\n return x.back();\r\n }\r\n\r\n /// \r\n /// Get the (n)th Root\r\n /// Code based mostly from https://rosettacode.org/wiki/Nth_root#C.23\r\n /// \r\n /// The n value to apply with root.\r\n /// \r\n static MediumDec NthRootV5(MediumDec targetValue, int n, MediumDec& Precision=MediumDec::FiveBillionth)\r\n {\r\n int nMinus1 = n - 1;\r\n MediumDec x[2] = { (MediumDec::One / n) * ((nMinus1 * targetValue) + (targetValue / MediumDec::Pow(targetValue, nMinus1))), targetValue };\r\n while (MediumDec::Abs(x[0] - x[1]) > Precision)\r\n {\r\n x[1] = x[0];\r\n x[0] = (MediumDec::One / n) * ((nMinus1 * x[1]) + (targetValue / MediumDec::Pow(x[1], nMinus1)));\r\n }\r\n return x[0];\r\n }\r\n\r\n /// \r\n /// Log Base 10 of Value\r\n /// \r\n /// The value.\r\n /// MediumDec\r\n static MediumDec Log10(MediumDec Value)\r\n {\r\n return MediumDec::Ln(Value) / MediumDec::LN10;\r\n }\r\n\r\n /// \r\n /// Log Base 10 of Value\r\n /// \r\n /// The value.\r\n /// MediumDec\r\n static MediumDec Log10(int Value)\r\n {\r\n return MediumDec::Ln(Value) / MediumDec::LN10;\r\n }\r\n\r\n /// \r\n /// Log with Base of BaseVal of Value\r\n /// Based on http://home.windstream.net/okrebs/page57.html\r\n /// \r\n /// The value.\r\n /// The base of Log\r\n /// MediumDec\r\n static MediumDec Log(MediumDec Value, MediumDec BaseVal)\r\n {\r\n return Log10(Value) / Log10(BaseVal);\r\n }\r\n\r\n /// \r\n /// Log with Base of BaseVal of Value\r\n /// Based on http://home.windstream.net/okrebs/page57.html\r\n /// \r\n /// The value.\r\n /// The base of Log\r\n /// MediumDec\r\n static MediumDec Log(MediumDec Value, int BaseVal)\r\n {\r\n return Log10(Value) / Log10(BaseVal);\r\n }\r\n\r\n /// \r\n /// Natural log\r\n /// \r\n /// The target value.\r\n static MediumDec Ln(MediumDec value)\r\n {\r\n //if (value <= 0) {}else//Error if equal or less than 0\r\n if (value == MediumDec::One)\r\n return MediumDec::Zero;\r\n else if (value.IntValue < 2)//Threshold between 0 and 2 based on Taylor code series from https://stackoverflow.com/questions/26820871/c-program-which-calculates-ln-for-a-given-variable-x-without-using-any-ready-f\r\n {//This section gives correct answer\r\n MediumDec threshold = \"0.00005\"; // set this to whatever threshold you want\r\n MediumDec base = value - 1; // Base of the numerator; exponent will be explicit\r\n int den = 1; // Denominator of the nth term\r\n bool posSign = true; // Used to swap the sign of each term\r\n MediumDec term = base; // First term\r\n MediumDec prev = 0; // Previous sum\r\n MediumDec result = term; // Kick it off\r\n\r\n while (MediumDec::Abs(prev - result) > threshold) {\r\n den++;\r\n posSign = !posSign;\r\n term *= base;\r\n prev = result;\r\n if (posSign)\r\n result += term / den;\r\n else\r\n result -= term / den;\r\n }\r\n\r\n return result;\r\n }\r\n else//Returns a positive value(http://www.netlib.org/cephes/qlibdoc.html#qlog)\r\n {//Increasing iterations brings closer to accurate result\r\n MediumDec W = (value - 1) / (value + 1);\r\n MediumDec TotalRes = W;\r\n#if(_DEBUG)\r\n MediumDec AddRes = MediumDec::Maximum;\r\n int WPow;\r\n for(WPow=3; AddRes>MediumDec::JustAboveZero;WPow+=2)\r\n {\r\n AddRes = MediumDec::PowRef(W, WPow) / WPow;\r\n TotalRes += AddRes;\r\n }\r\n TotalRes *= 2;\r\n std::cout << \"Ln(\" << value.ToString() << \") = \" << TotalRes.ToString() << \" FloatingResult:\" << log((double)value) <<\" WPow:\"<< WPow <<\" AddRes:\"<\r\n /// Natural log (Equivalent to Log_E(value))\r\n /// \r\n /// The target value.\r\n /// The threshold value for when value is between 0 and 2.\r\n /// BlazesRusCode::MediumDec\r\n static MediumDec LnRef(MediumDec& value, MediumDec threshold)\r\n {\r\n //if (value <= 0) {}else//Error if equal or less than 0\r\n if (value == MediumDec::One)\r\n return MediumDec::Zero;\r\n else if (value.IntValue < 2)//Threshold between 0 and 2 based on Taylor code series from https://stackoverflow.com/questions/26820871/c-program-which-calculates-ln-for-a-given-variable-x-without-using-any-ready-f\r\n {//This section gives accurate answer\r\n MediumDec base = value - 1; // Base of the numerator; exponent will be explicit\r\n int den = 1; // Denominator of the nth term\r\n bool posSign = true; // Used to swap the sign of each term\r\n MediumDec term = base; // First term\r\n MediumDec prev = 0; // Previous sum\r\n MediumDec result = term; // Kick it off\r\n\r\n while (MediumDec::Abs(prev - result) > threshold) {\r\n den++;\r\n posSign = !posSign;\r\n term *= base;\r\n prev = result;\r\n if (posSign)\r\n result += term / den;\r\n else\r\n result -= term / den;\r\n }\r\n\r\n return result;\r\n }\r\n else//Returns a positive value(http://www.netlib.org/cephes/qlibdoc.html#qlog)\r\n {//Increasing iterations brings closer to accurate result(Larger numbers need more iterations to get accurate level of result)\r\n MediumDec W = (value - 1) / (value + 1);\r\n MediumDec TotalRes = W;\r\n MediumDec AddRes;\r\n //for (int WPow = 3; AddRes > MediumDec::JustAboveZero; WPow += 2)\r\n int WPow = 3;\r\n do\r\n {\r\n AddRes = MediumDec::PowRef(W, WPow) / WPow;\r\n TotalRes += AddRes; WPow += 2;\r\n } while (AddRes > MediumDec::JustAboveZero);\r\n return TotalRes * 2;\r\n }\r\n }\r\n\r\n /// \r\n /// Natural log (Equivalent to Log_E(value))\r\n /// \r\n /// The target value.\r\n static MediumDec Ln(MediumDec value, MediumDec threshold)\r\n {\r\n return LnRef(value, threshold);\r\n }\r\n\r\n /// \r\n /// Natural log TestVersion(Equivalent to Log_E(value))\r\n /// \r\n /// The target value.\r\n /// double\r\n static MediumDec LnTestRef(double& fvalue, MediumDec& value)\r\n {\r\n //if (value <= 0) {}else//Error if equal or less than 0\r\n if (value==MediumDec::One)\r\n return MediumDec::Zero;\r\n if (value.IntValue==0)//Returns a negative number derived from (http://www.netlib.org/cephes/qlibdoc.html#qlog)\r\n {\r\n double fW = (fvalue - 1.0);\r\n MediumDec W = (value - 1);\r\n std::cout << \"--Floating W Numerator:\" << fW << \" vs \" << W.ToString() << \"--\" << std::endl;\r\n double fDenom = (fvalue + 1.0);\r\n fW /= fDenom;//(-0.5)/(1.5)=-1/3\r\n MediumDec Denom = (value + 1);\r\n std::cout << \"--Floating W Denom:\" << fDenom << \" vs \" << Denom.ToString() << \"--\" << std::endl;\r\n W /= Denom;\r\n double fTotalRes = fW;\r\n fW *= -1;\r\n double fLastPow = fW;\r\n double fWSquared = fW * fW;\r\n double fAddRes;\r\n int WPow = 3;\r\n\r\n MediumDec TotalRes = W;\r\n W.SwapNegativeStatus();\r\n MediumDec LastPow = W;\r\n MediumDec WSquared = W * W;\r\n MediumDec AddRes;\r\n std::cout << \"--Floating W:\" << fW << \" vs \" << W.ToString() << \"--\" << std::endl;\r\n do\r\n {\r\n fLastPow *= fWSquared;\r\n LastPow *= WSquared;\r\n //std::cout << \"-----Floating LastPow:\" << fLastPow << \" vs \" << LastPow.ToString() << \"--\" << std::endl;\r\n\r\n fAddRes = fLastPow / WPow;\r\n AddRes = LastPow / WPow;\r\n //std::cout << \"-----Floating AddRes:\" << fAddRes << \" vs \" << AddRes.ToString() << \"--\" << std::endl;\r\n\r\n fTotalRes -= fAddRes;\r\n TotalRes -= AddRes;\r\n\r\n WPow += 2;\r\n } while (AddRes > MediumDec::JustAboveZero);//Total Result should be -0.346573590279972654708616060729088284037750067180127627060340004746696810984847357802931663498209344\r\n return TotalRes * 2;//Should result in -0.693147180559\r\n }\r\n else if(value.IntValue==1)\r\n {\r\n MediumDec threshold = MediumDec::FiveMillionth;\r\n MediumDec base = value - 1; // Base of the numerator; exponent will be explicit\r\n int den = 2; // Denominator of the nth term\r\n bool posSign = true; // Used to swap the sign of each term\r\n MediumDec term = base; // First term\r\n MediumDec prev; // Previous sum\r\n MediumDec result = term; // Kick it off\r\n\r\n do\r\n {\r\n posSign = !posSign;\r\n term *= base;\r\n prev = result;\r\n if (posSign)\r\n result += term / den;\r\n else\r\n result -= term / den;\r\n den++;\r\n } while (MediumDec::Abs(prev - result) > threshold);\r\n\r\n return result;\r\n }\r\n else//Returns a positive value(http://www.netlib.org/cephes/qlibdoc.html#qlog)\r\n {//Increasing iterations brings closer to accurate result(Larger numbers need more iterations to get accurate level of result)\r\n MediumDec TotalRes = (value - 1) / (value + 1);//W;\r\n MediumDec LastPow = TotalRes;\r\n MediumDec WSquared = TotalRes * TotalRes;\r\n MediumDec AddRes;\r\n int WPow = 3;\r\n do\r\n {\r\n LastPow *= WSquared;\r\n AddRes = LastPow / WPow;//MediumDec::PowRef(W, WPow) / WPow;\r\n TotalRes += AddRes; WPow += 2;\r\n } while (AddRes > MediumDec::JustAboveZero);\r\n return TotalRes * 2;\r\n }\r\n }\r\n\r\n /// \r\n /// Natural log (Equivalent to Log_E(value))\r\n /// \r\n /// The target value.\r\n static MediumDec LnTest(double fvalue, MediumDec value)\r\n {\r\n return LnTestRef(fvalue, value);\r\n }\r\n}", "meta": {"hexsha": "7c41e76761f6a180e69c83bfbaeac6c900bbae73", "size": 15355, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SharedCode/AltNum/AltNumDebug.hpp", "max_stars_repo_name": "BlazesRus/BlazesRusSharedCode", "max_stars_repo_head_hexsha": "1925f11afca9476bbbd79df35f77e143418b4799", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-04-05T03:59:40.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-16T08:39:39.000Z", "max_issues_repo_path": "SharedCode/AltNum/AltNumDebug.hpp", "max_issues_repo_name": "BlazesRus/BlazesRusSharedCode", "max_issues_repo_head_hexsha": "1925f11afca9476bbbd79df35f77e143418b4799", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-01-28T00:07:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-28T00:07:53.000Z", "max_forks_repo_path": "SharedCode/AltNum/AltNumDebug.hpp", "max_forks_repo_name": "BlazesRus/MultiPlatformGlobalCode", "max_forks_repo_head_hexsha": "1925f11afca9476bbbd79df35f77e143418b4799", "max_forks_repo_licenses": ["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.7255434783, "max_line_length": 221, "alphanum_fraction": 0.5189189189, "num_tokens": 3801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7541962685356313}} {"text": "#define _USE_MATH_DEFINES\n#include \n#include \n\nusing namespace std;\n\n#include \n#include \n\nusing namespace Eigen;\n\n//本程式演示了 Eigen 幾何模組的使用方法\n\nint main(int argc, char** argv) {\n\n\t// Eigen/Geometry 模組提供了各種旋轉和平移的表示方法\n\t// 3D 旋轉矩陣直接使用 Matrix3d 或 Matrix3f\n\tMatrix3d rotation_matrix = Matrix3d::Identity();\n\t// 旋轉向量使用 AngleAxis,它底層不是Matrix,但運算可以當作矩陣(因為運算子超載)\n\tAngleAxisd rotation_vector(M_PI / 4, Vector3d(0, 0, 1)); //沿 Z 軸旋轉 45 度\n\tcout.precision(3);\n\tcout << \"rotation matrix =\\n\" << rotation_vector.matrix() << endl; //用matrix()轉換成矩陣\n\t// 也可以直接賦值\n\trotation_matrix = rotation_vector.toRotationMatrix();\n\t// 用 AngleAxis 可以進行座標變換\n\tVector3d v(1, 0, 0);\n\tVector3d v_rotated = rotation_vector * v;\n\tcout << \"(1,0,0) after rotation (by angle axis) = \" << v_rotated.transpose() << endl;\n\t// 或者用旋轉矩陣\n\tv_rotated = rotation_matrix * v;\n\tcout << \"(1,0,0) after rotation (by matrix) = \" << v_rotated.transpose() << endl;\n\n\t// 尤拉角: 可以將旋轉矩陣直接轉換成尤拉角\n\tVector3d euler_angles = rotation_matrix.eulerAngles(2, 1, 0); // ZYX順序,即yaw-pitch-roll順序\n\tcout << \"yaw pitch roll = \" << euler_angles.transpose() << endl;\n\n\t// 歐氏變換矩陣使用 Eigen::Isometry\n\tIsometry3d T = Isometry3d::Identity(); // 雖然稱為3d,實質上是4*4的矩陣\n\tT.rotate(rotation_vector); // 按照rotation_vector進行旋轉\n\tT.pretranslate(Vector3d(1, 3, 4)); // 把平移向量設成(1,3,4)\n\tcout << \"Transform matrix = \\n\" << T.matrix() << endl;\n\n\t// 用變換矩陣進行座標變換\n\tVector3d v_transformed = T * v; // 相當於R*v+t\n\tcout << \"v tranformed = \" << v_transformed.transpose() << endl;\n\n\t// 對於仿射和射影變換,使用 Eigen::Affine3d 和 Eigen::Projective3d 即可,略\n\n\t// 四元數\n\t// 可以直接把AngleAxis賦值给四元數,反之亦然\n\tQuaterniond q = Quaterniond(rotation_vector);\n\tcout << \"quaternion from rotation vector = \" << q.coeffs().transpose()\n\t\t<< endl; // 請注意coeffs的順序是(x,y,z,w),w為實部,前三者為虛部\n // 也可以把旋轉矩陣賦給它\n\tq = Quaterniond(rotation_matrix);\n\tcout << \"quaternion from rotation matrix = \" << q.coeffs().transpose() << endl;\n\t// 使用四元數旋轉一个向量,使用超載的乘法即可\n\tv_rotated = q * v; // 注意數學上是qvq^{-1}\n\tcout << \"(1,0,0) after rotation = \" << v_rotated.transpose() << endl;\n\t// 用常規向量乘法表示,則應該如下計算\n\tcout << \"should be equal to \" << (q * Quaterniond(0, 1, 0, 0) * q.inverse()).coeffs().transpose() << endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "f3c5eecaaa07426fae840d75d3212c123dd058b6", "size": 2288, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/useGeometry/eigenGeometry.cpp", "max_stars_repo_name": "jwaiting/slambook2", "max_stars_repo_head_hexsha": "1f6362c4c231b81129aa9894fd18f966156b52d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch3/useGeometry/eigenGeometry.cpp", "max_issues_repo_name": "jwaiting/slambook2", "max_issues_repo_head_hexsha": "1f6362c4c231b81129aa9894fd18f966156b52d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch3/useGeometry/eigenGeometry.cpp", "max_forks_repo_name": "jwaiting/slambook2", "max_forks_repo_head_hexsha": "1f6362c4c231b81129aa9894fd18f966156b52d6", "max_forks_repo_licenses": ["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.2, "max_line_length": 107, "alphanum_fraction": 0.6560314685, "num_tokens": 1020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539661002182845, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.7541391322674045}} {"text": "// This program is free software: you can use, modify and/or redistribute it\n// under the terms of the simplified BSD License. You should have received a\n// copy of this license along this program. If not, see\n// .\n//\n// Copyright (C) 2021, Thibaud Briand \n// Copyright (C) 2021, Jonathan Vacher \n// All rights reserved.\n\n#include \n#include \n#include \"Eigen/Dense\"\n#include \n\nusing namespace Eigen;\nusing namespace std;\n\n// Compute the color covariance matrix of a color image (Equation 97)\n// The mean of each channel of the input is assumed to be 0\nvoid compute_covariance(float *im, float C[3][3], int N)\n{\n int i, l;\n MatrixXf U(3,N);\n\n // put input data in a matrix\n for(l = 0; l < 3; l++)\n for(i = 0; i < N; i++)\n U(l,i) = im[i + l*N];\n\n // compute the color covariance matrix (Equation 97)\n Matrix3f cov = U*(U.transpose())/N;\n\n // put the covariance matrix in 3x3 array\n for(i = 0; i < 3; i++)\n for(l = 0; l < 3; l++)\n C[i][l] = cov(i,l);\n}\n\n// Compute the eigenvector decomposition of a symmetric matrix\n// We have A = V*diag(d)*V' where:\n// 1) V is an orthogonal matrix containing the eigenvectors\n// 2) d contains the eigenvalues\nvoid eigen_decomposition(const float A[3][3], float V[3][3], float d[3])\n{\n int i, j;\n Matrix3f C;\n\n // put array A in a matrix C\n for(i = 0; i < 3; i++)\n for(j = 0; j < 3; j++)\n C(i,j) = A[i][j];\n\n // eigen solver\n SelfAdjointEigenSolver eigensolver(C);\n\n // eigenvectors\n Matrix3f P = eigensolver.eigenvectors();\n for(i = 0; i < 3; i++)\n for(j = 0; j < 3; j++)\n V[i][j] = P(i,j);\n\n // eigenvalues\n Vector3f E = eigensolver.eigenvalues();\n for(i = 0; i < 3; i++)\n d[i] = E(i);\n}\n\n// Apply the direct PCA transform (Equation 99)\n// out = diag(d)^{-1/2}*V'*in\n// The mean of each channel of the input is assumed to be 0\nvoid apply_pca(float *out, const float *in, const float V[3][3],\n const float d[3], int N)\n{\n int i, l;\n\n // put data in matrices\n MatrixXf U(3,N);\n for(l = 0; l < 3; l++)\n for(i = 0; i < N; i++)\n U(l,i) = in[i + l*N];\n\n Matrix3f V2;\n for(l = 0; l < 3; l++)\n for(i = 0; i < 3; i++)\n V2(i,l) = V[i][l];\n\n // compute d^{-1/2}\n // eigenvalues smaller than 1e-2 are set to 0 to avoid instability\n // this is useless when the function sanity_check was used to handle\n // input images with strange content\n Vector3f d2;\n for(l = 0; l < 3; l++)\n d2(l) = (d[l] < 1e-2) ? 0 : 1.0/sqrt(d[l]);\n\n // apply direct PCA transform (Equation 82)\n // out = diag(d)^{-1/2}*V'*in\n U = (d2.asDiagonal())*(V2.transpose())*U;\n\n // put the computed matrix in the output array\n for(l = 0; l < 3; l++)\n for(i = 0; i < N; i++)\n out[i + l*N] = U(l,i);\n}\n\n// Apply the inverse PCA transform (Equation 100)\n// out = V*diag(d)^{1/2}*in\n// The mean of each channel of the input is assumed to be 0\nvoid apply_inverse_pca(float *out, const float *in, const float V[3][3],\n const float d[3], int N)\n{\n int i, l;\n\n // put data in matrices\n MatrixXf tildeU(3,N);\n for(l = 0; l < 3; l++)\n for(i = 0; i < N; i++)\n tildeU(l,i) = in[i + l*N];\n\n Matrix3f V2;\n for(l = 0; l < 3; l++)\n for(i = 0; i < 3; i++)\n V2(i,l) = V[i][l];\n\n // compute d^{1/2}\n Vector3f d2;\n for(l = 0; l < 3; l++)\n d2(l) = sqrt(d[l]);\n\n // apply inverse PCA transform (Equation 83)\n // out = V*diag(d)^{1/2}*in\n tildeU = V2*(d2.asDiagonal())*tildeU;\n\n // put the computed matrix in the output array\n for(l = 0; l < 3; l++)\n for(i = 0; i < N; i++)\n out[i + l*N] = tildeU(l,i);\n}\n", "meta": {"hexsha": "616f7662c43cf99fb58607434735e509402ca1aa", "size": 3703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pca.cpp", "max_stars_repo_name": "tbriand/portilla-simoncelli-ipol", "max_stars_repo_head_hexsha": "d867d9a22418dca23f0a2e55a6e0b49b8e33b703", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pca.cpp", "max_issues_repo_name": "tbriand/portilla-simoncelli-ipol", "max_issues_repo_head_hexsha": "d867d9a22418dca23f0a2e55a6e0b49b8e33b703", "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/pca.cpp", "max_forks_repo_name": "tbriand/portilla-simoncelli-ipol", "max_forks_repo_head_hexsha": "d867d9a22418dca23f0a2e55a6e0b49b8e33b703", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8333333333, "max_line_length": 76, "alphanum_fraction": 0.5843910343, "num_tokens": 1307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.7541167963023655}} {"text": "#include \"WindingNumbers.h\"\r\n#include \"SPlisHSPlasH/Common.h\"\r\n#include \r\n\r\n#define _USE_MATH_DEFINES\r\n#include \"math.h\"\r\n\r\nusing namespace Utilities;\r\nusing namespace SPH;\r\nusing namespace Eigen;\r\n\r\n\r\nReal WindingNumbers::computeGeneralizedWindingNumber(const Vector3r& p_, const Vector3r& a_, const Vector3r& b_, const Vector3r& c_)\r\n{\r\n \tconst Vector3r& a = a_ - p_;\r\n \tconst Vector3r& b = b_ - p_;\r\n \tconst Vector3r& c = c_ - p_;\r\n \t\r\n \tconst Real normA = a.norm();\r\n \tconst Real normB = b.norm();\r\n \tconst Real normC = c.norm();\r\n \r\n\tMatrix3r A;\r\n\tA.row(0) = a;\r\n\tA.row(1) = b;\r\n\tA.row(2) = c;\r\n \tconst Real det = A.determinant();\r\n \tconst Real divisor = normA*normB*normC + (a.dot(b))*normC + (b.dot(c))*normA + (c.dot(a))*normB;\r\n \r\n \tstatic const Real tau = 2.0 * M_PI;\r\n \treturn std::atan2(det,divisor) / tau; // Only divide by 2*pi instead of 4*pi because there was a 2 out front\r\n}\r\n\r\nReal WindingNumbers::computeGeneralizedWindingNumber(const Vector3r& p, const TriangleMesh& mesh)\r\n{\r\n \tconst unsigned int *faces = mesh.getFaces().data();\r\n \tconst unsigned int nFaces = mesh.numFaces();\r\n\tconst Vector3r *v = mesh.getVertices().data();\r\n \r\n \t// compute generalized winding number\r\n \tReal w_p = 0;\r\n \t#pragma omp parallel for reduction (+: w_p)\r\n \tfor (int idx = 0; idx < static_cast(nFaces); idx ++)\r\n \t{\r\n \t\tconst Vector3r& a = v[faces[idx*3+0]];\r\n \t\tconst Vector3r& b = v[faces[idx*3+1]];\r\n \t\tconst Vector3r& c = v[faces[idx*3+2]];\r\n \r\n \t\tw_p += computeGeneralizedWindingNumber(p, a, b, c);\r\n \t}\r\n \r\n \treturn w_p;\r\n}\r\n", "meta": {"hexsha": "04ec78ede8c4661a5cd9cf3d3e83ec473c958d9f", "size": 1552, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SPlisHSPlasH/Utilities/WindingNumbers.cpp", "max_stars_repo_name": "horizon-research/SPlisHSPlasH_with_time", "max_stars_repo_head_hexsha": "147ada04d35e354f9cb01675834c1bd80e1b1d23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SPlisHSPlasH/Utilities/WindingNumbers.cpp", "max_issues_repo_name": "horizon-research/SPlisHSPlasH_with_time", "max_issues_repo_head_hexsha": "147ada04d35e354f9cb01675834c1bd80e1b1d23", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SPlisHSPlasH/Utilities/WindingNumbers.cpp", "max_forks_repo_name": "horizon-research/SPlisHSPlasH_with_time", "max_forks_repo_head_hexsha": "147ada04d35e354f9cb01675834c1bd80e1b1d23", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7407407407, "max_line_length": 133, "alphanum_fraction": 0.6514175258, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159683, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7537766019420706}} {"text": "#ifndef MATHTOOLBOX_DATA_NORMALIZATION_HPP\n#define MATHTOOLBOX_DATA_NORMALIZATION_HPP\n\n#include \n\nnamespace mathtoolbox\n{\n class DataNormalizer\n {\n public:\n /// \\param data_points An n-by-m matrix representing m data points lying in an n-dimensional space.\n DataNormalizer(const Eigen::MatrixXd& data_points) : m_original_data_points(data_points)\n {\n const int num_dims = m_original_data_points.rows();\n const int num_data_points = m_original_data_points.cols();\n\n assert(num_dims > 0);\n assert(num_data_points > 0);\n\n m_mean = Eigen::VectorXd(num_dims);\n m_stdev = Eigen::VectorXd(num_dims);\n\n for (int dim = 0; dim < num_dims; ++dim)\n {\n const Eigen::VectorXd one_dim_data = m_original_data_points.row(dim);\n\n m_mean(dim) = one_dim_data.mean();\n m_stdev(dim) =\n std::sqrt((one_dim_data - Eigen::VectorXd::Constant(num_data_points, m_mean(dim))).squaredNorm() /\n static_cast(num_data_points));\n }\n\n m_normalized_data_points = Normalize(m_original_data_points);\n }\n\n /// \\brief Get the normalized data points.\n const Eigen::MatrixXd& GetNormalizedDataPoints() const { return m_normalized_data_points; }\n\n /// \\brief Normalize a new set of data points by the same transformation as the originally provided data points.\n Eigen::MatrixXd Normalize(const Eigen::MatrixXd& data_points) const\n {\n const int num_dims = data_points.rows();\n const int num_data_points = data_points.cols();\n\n Eigen::MatrixXd normalized_data_points(num_dims, num_data_points);\n for (int dim = 0; dim < num_dims; ++dim)\n {\n constexpr double epsilon = 1e-32;\n const double scale = 1.0 / std::max(m_stdev(dim), epsilon);\n const auto offset = Eigen::VectorXd::Constant(num_data_points, m_mean(dim));\n\n normalized_data_points.row(dim) = scale * (data_points.row(dim) - offset.transpose());\n }\n\n return normalized_data_points;\n }\n\n /// \\brief Denormalize a new set of data points that is represented as the normalized form.\n Eigen::MatrixXd Denormalize(const Eigen::MatrixXd& normalized_data_points) const\n {\n const int num_dims = normalized_data_points.rows();\n const int num_data_points = normalized_data_points.cols();\n\n Eigen::MatrixXd data_points(num_dims, num_data_points);\n for (int dim = 0; dim < num_dims; ++dim)\n {\n constexpr double epsilon = 1e-32;\n const double scale = std::max(m_stdev(dim), epsilon);\n const auto offset = Eigen::VectorXd::Constant(num_data_points, m_mean(dim));\n\n data_points.row(dim) = scale * normalized_data_points.row(dim) + offset.transpose();\n }\n\n return data_points;\n }\n\n /// \\brief Get internal parameters about the means.\n const Eigen::VectorXd& GetMean() const { return m_mean; }\n\n /// \\brief Get internal parameters about the standard deviations.\n const Eigen::VectorXd& GetStdev() const { return m_stdev; }\n\n private:\n const Eigen::MatrixXd m_original_data_points;\n\n Eigen::MatrixXd m_normalized_data_points;\n Eigen::VectorXd m_mean;\n Eigen::VectorXd m_stdev;\n };\n} // namespace mathtoolbox\n\n#endif // MATHTOOLBOX_DATA_NORMALIZATION_HPP\n", "meta": {"hexsha": "b1daf610097367d7b1a75684923cae6d9a33ef9a", "size": 3661, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/data-normalization.hpp", "max_stars_repo_name": "yuki-koyama/mathtoolbox", "max_stars_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 195.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T16:12:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:52:56.000Z", "max_issues_repo_path": "include/mathtoolbox/data-normalization.hpp", "max_issues_repo_name": "yuki-koyama/mathtoolbox", "max_issues_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2018-04-15T01:24:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T09:14:23.000Z", "max_forks_repo_path": "include/mathtoolbox/data-normalization.hpp", "max_forks_repo_name": "yuki-koyama/mathtoolbox", "max_forks_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T04:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:28:12.000Z", "avg_line_length": 39.3655913978, "max_line_length": 120, "alphanum_fraction": 0.6137667304, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7536388119753847}} {"text": "#pragma once\r\n\r\n#ifdef BOOST_UBLAS_TYPE_CHECK\r\n#\tundef BOOST_UBLAS_TYPE_CHECK\r\n#endif\r\n#define BOOST_UBLAS_TYPE_CHECK 0\r\n#ifndef _USE_MATH_DEFINES\r\n#\tdefine _USE_MATH_DEFINES\r\n#endif\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n/*\r\n\tFinds the coefficients of a polynomial p(x) of degree n that fits the data, \r\n\tp(x(i)) to y(i), in a least squares sense. The result p is a row vector of \r\n\tlength n+1 containing the polynomial coefficients in incremental powers.\r\n\r\n\tparam:\r\n\t\toX\t\t\t\tx axis values\r\n\t\toY\t\t\t\ty axis values\r\n\t\tnDegree\t\t\tpolynomial degree including the constant\r\n\r\n\treturn:\r\n\t\tcoefficients of a polynomial starting at the constant coefficient and\r\n\t\tending with the coefficient of power to nDegree. C++0x-compatible \r\n\t\tcompilers make returning locally created vectors very efficient.\r\n\r\n*/\r\ntemplate\r\nstd::vector polyfit( const std::vector& oX, const std::vector& oY, int nDegree )\r\n{\r\n\tusing namespace boost::numeric::ublas;\r\n\r\n\tif ( oX.size() != oY.size() )\r\n\t\tthrow std::invalid_argument( \"X and Y vector sizes do not match\" );\r\n\r\n\t// more intuative this way\r\n\tnDegree++;\r\n\t\r\n\tsize_t nCount = oX.size();\r\n\tmatrix oXMatrix( nCount, nDegree );\r\n\tmatrix oYMatrix( nCount, 1 );\r\n\t\r\n\t// copy y matrix\r\n\tfor ( size_t i = 0; i < nCount; i++ )\r\n\t{\r\n\t\toYMatrix(i, 0) = oY[i];\r\n\t}\r\n\r\n\t// create the X matrix\r\n\tfor ( size_t nRow = 0; nRow < nCount; nRow++ )\r\n\t{\r\n\t\tT nVal = 1.0f;\r\n\t\tfor ( int nCol = 0; nCol < nDegree; nCol++ )\r\n\t\t{\r\n\t\t\toXMatrix(nRow, nCol) = nVal;\r\n\t\t\tnVal *= oX[nRow];\r\n\t\t}\r\n\t}\r\n\r\n\t// transpose X matrix\r\n\tmatrix oXtMatrix( trans(oXMatrix) );\r\n\t// multiply transposed X matrix with X matrix\r\n\tmatrix oXtXMatrix( prec_prod(oXtMatrix, oXMatrix) );\r\n\t// multiply transposed X matrix with Y matrix\r\n\tmatrix oXtYMatrix( prec_prod(oXtMatrix, oYMatrix) );\r\n\r\n\t// lu decomposition\r\n\tpermutation_matrix pert(oXtXMatrix.size1());\r\n\tconst std::size_t singular = lu_factorize(oXtXMatrix, pert);\r\n\t// must be singular\r\n\tBOOST_ASSERT( singular == 0 );\r\n\r\n\t// backsubstitution\r\n\tlu_substitute(oXtXMatrix, pert, oXtYMatrix);\r\n\r\n\t// copy the result to coeff\r\n\treturn std::vector( oXtYMatrix.data().begin(), oXtYMatrix.data().end() );\r\n}\r\n\r\n/*\r\n\tCalculates the value of a polynomial of degree n evaluated at x. The input \r\n\targument pCoeff is a vector of length n+1 whose elements are the coefficients \r\n\tin incremental powers of the polynomial to be evaluated.\r\n\r\n\tparam:\r\n\t\toCoeff\t\t\tpolynomial coefficients generated by polyfit() function\r\n\t\toX\t\t\t\tx axis values\r\n\r\n\treturn:\r\n\t\tFitted Y values. C++0x-compatible compilers make returning locally \r\n\t\tcreated vectors very efficient.\r\n*/\r\ntemplate\r\nstd::vector polyval( const std::vector& oCoeff, const std::vector& oX )\r\n{\r\n\tsize_t nCount = oX.size();\r\n\tsize_t nDegree = oCoeff.size();\r\n\tstd::vector\toY( nCount );\r\n\r\n\tfor ( size_t i = 0; i < nCount; i++ )\r\n\t{\r\n\t\tT nY = 0;\r\n\t\tT nXT = 1;\r\n\t\tT nX = oX[i];\r\n\t\tfor ( size_t j = 0; j < nDegree; j++ )\r\n\t\t{\r\n\t\t\t// multiply current x by a coefficient\r\n\t\t\tnY += oCoeff[j] * nXT;\r\n\t\t\t// power up the X\r\n\t\t\tnXT *= nX;\r\n\t\t}\r\n\t\toY[i] = nY;\r\n\t}\r\n\r\n\treturn oY;\r\n}\r\n", "meta": {"hexsha": "739cb0d160c633dd1b8679cedd2af7f38c48f577", "size": 3258, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utils/polyfit.hpp", "max_stars_repo_name": "fryegg/pingpong", "max_stars_repo_head_hexsha": "134dffcadb3d07ca0a97b725814f3b090e50be87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/polyfit.hpp", "max_issues_repo_name": "fryegg/pingpong", "max_issues_repo_head_hexsha": "134dffcadb3d07ca0a97b725814f3b090e50be87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/polyfit.hpp", "max_forks_repo_name": "fryegg/pingpong", "max_forks_repo_head_hexsha": "134dffcadb3d07ca0a97b725814f3b090e50be87", "max_forks_repo_licenses": ["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.487804878, "max_line_length": 90, "alphanum_fraction": 0.6654389196, "num_tokens": 953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8479677506936878, "lm_q1q2_score": 0.7536388000240308}} {"text": "#include \n\n#include \n#include \n\nnamespace InterPose {\nnamespace Utils {\n\n // -1 <= cos_theta <= 1, 0 <= theta <= pi\n const double EPS_to_0 = 1e-5;\n const double EPS_to_1 = 1.0 - 1e-5;\n\n template \n Eigen::Matrix log(const Eigen::Matrix& R, TYPE& theta) {\n Eigen::Matrix omega_x;\n\n const TYPE cos_theta = (R.trace() - 1.0)/2.0; \n\n if(cos_theta < -EPS_to_1) { // need to handle theta = pi\n Eigen::Matrix R_plus_I = R + Eigen::Matrix::Identity();\n int _col = -1;\n TYPE longest_col_length = -1.0;\n for(int c = 0; c < 3; ++c) {\n TYPE length = R_plus_I.col(c).norm();\n if(length > longest_col_length) {\n _col = c;\n longest_col_length = length;\n }\n\n theta = M_PI;\n const Eigen::Matrix omega = (M_PI/longest_col_length)\n * Eigen::Matrix(R_plus_I(0,_col), R_plus_I(1,_col), R_plus_I(2,_col));\n omega_x(0,0) = 0.0; omega_x(0,1) = -omega(2); omega_x(0,2) = omega(1);\n omega_x(1,0) = omega(2); omega_x(1,1) = 0; omega_x(1,2) = -omega(0);\n omega_x(2,0) = -omega(1); omega_x(2,1) = omega(0); omega_x(2,2) = 0.0;\n }\n }\n else if (cos_theta > EPS_to_1) { // need to handle theta = 0\n const TYPE _theta = std::acos((R.trace() - 1.0)/2.0);\n const Eigen::Matrix _omega_x = 0.5*(1.0 + _theta*_theta/6.0)*(R - R.transpose()); // log(R)\n\n omega_x = _omega_x;\n theta = _theta;\n }\n else { // usual case\n const TYPE _theta = std::acos(cos_theta);\n const Eigen::Matrix _omega_x = _theta*(R - R.transpose())/(2.0*std::sin(_theta)); // log(R)\n\n omega_x = _omega_x;\n theta = _theta;\n }\n\n return omega_x;\n }\n\n template \n Eigen::Matrix exp(const Eigen::Matrix& w, const Eigen::Matrix& t, const TYPE& theta) {\n Eigen::Matrix T = Eigen::Matrix4d::Identity();\n Eigen::Matrix w_x;\n w_x(0,0) = 0.0; w_x(0,1) = -w(2); w_x(0,2) = w(1);\n w_x(1,0) = w(2); w_x(1,1) = 0; w_x(1,2) = -w(0);\n w_x(2,0) = -w(1); w_x(2,1) = w(0); w_x(2,2) = 0.0;\n\n if(theta < EPS_to_0) {\n Eigen::Matrix e_w_x = Eigen::Matrix::Identity(); \n T.block(0,0,3,3) = e_w_x;\n T.block(0,3,3,1) = e_w_x * t;\n }\n else {\n Eigen::Matrix e_w_x = Eigen::Matrix::Identity() \n + (std::sin(theta)/theta)*w_x\n + ((1.0-std::cos(theta))/(theta*theta))*w_x*w_x;\n \n Eigen::Matrix V = Eigen::Matrix::Identity() \n + ((1.0-std::cos(theta))/(theta*theta))*w_x\n + ((theta - std::sin(theta))/(theta*theta*theta))*w_x*w_x;\n\n Eigen::Matrix _t = V * t;\n\n T.block(0,0,3,3) = e_w_x;\n T.block(0,3,3,1) = _t;\n }\n\n return T;\n }\n}\n}\n", "meta": {"hexsha": "e55ddd5840e1ed00c126e861f99f928a1eedefea", "size": 3027, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Utils.hpp", "max_stars_repo_name": "cashiwamochi/InterPoseLib", "max_stars_repo_head_hexsha": "020f1067d459a1428c29000904e13ae1185290bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-12-22T00:02:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-17T14:08:56.000Z", "max_issues_repo_path": "src/Utils.hpp", "max_issues_repo_name": "cashiwamochi/InterPoseLib", "max_issues_repo_head_hexsha": "020f1067d459a1428c29000904e13ae1185290bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-12-21T11:13:30.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T05:23:27.000Z", "max_forks_repo_path": "src/Utils.hpp", "max_forks_repo_name": "cashiwamochi/InterPose", "max_forks_repo_head_hexsha": "020f1067d459a1428c29000904e13ae1185290bf", "max_forks_repo_licenses": ["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.3977272727, "max_line_length": 122, "alphanum_fraction": 0.5292368682, "num_tokens": 1111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750400464602, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.7535928282444367}} {"text": "#include \n#include \n#include \n//#include \n#ifndef EIGEN_PINV_HPP\n#define EIGEN_PINV_HPP\nnamespace EIGEN_PINV\n{\n// Derived from code by Yohann Solaro ( http://listengine.tuxfamily.org/lists.tuxfamily.org/eigen/2010/01/msg00187.html )\n// see : http://en.wikipedia.org/wiki/Moore-Penrose_pseudoinverse#The_general_case_and_the_SVD_method\nEigen::MatrixXd pinv( const Eigen::MatrixXd &b, double rcond )\n{\n // TODO: Figure out why it wants fewer rows than columns\n // if ( a.rows() svdA;\n svdA.compute( a, Eigen::ComputeFullU | Eigen::ComputeThinV );\n Eigen::JacobiSVD::SingularValuesType vSingular = svdA.singularValues();\n // Build a diagonal matrix with the Inverted Singular values\n // The pseudo inverted singular matrix is easy to compute :\n // is formed by replacing every nonzero entry by its reciprocal (inversing).\n Eigen::VectorXd vPseudoInvertedSingular( svdA.matrixV().cols() );\n\n for (int iRow=0; iRow\n#include \n#include \n#include \n\n#include \n\nusing namespace boost::geometry;\n\ntemplate\n<\n typename OutPoint,\n typename InPoint,\n typename Generator\n>\nOutPoint sample_triangle_uniform(const InPoint& p1, const InPoint& p2, const InPoint& p3, Generator& gen)\n{\n std::uniform_real_distribution<> dis(0, 1);\n double r1 = dis(gen);\n double r2 = dis(gen);\n return make(\n (1-std::sqrt(r1))*get<0>(p1)+\n (std::sqrt(r1)*(1-r2))*get<0>(p2)+\n (r2*std::sqrt(r1))*get<0>(p3),\n (1-std::sqrt(r1))*get<1>(p1)+\n (std::sqrt(r1)*(1-r2))*get<1>(p2)+\n (r2*std::sqrt(r1))*get<1>(p3));\n}\n\ntemplate\n<\n typename Polygon,\n typename Collection\n>\nvoid sample_polygon_uniform(const Polygon& p, std::size_t num, Collection& out)\n{\n typedef typename point_type::type point_type;\n typedef typename area_result::type area_type;\n typedef typename boost::range_value::type out_point_type;\n typename ring_type::type& ring = exterior_ring(p);\n const std::size_t length = boost::size(ring);\n std::vector::type> cumulative_area;\n cumulative_area.reserve(length-2);\n cumulative_area.push_back(0);\n area_type cum_sum = 0;\n for(std::size_t i = 1;i(*boost::begin(ring), *(boost::begin(ring)+i), *(boost::begin(ring)+i+1));\n cumulative_area.push_back(cum_sum);\n }\n\n std::random_device rd;\n std::mt19937 gen(rd());\n std::uniform_real_distribution<> dis(0, 1);\n for(std::size_t i = 0; i(dis(gen))*cum_sum;\n std::size_t t = std::distance(cumulative_area.begin(),\n std::lower_bound(cumulative_area.begin(),cumulative_area.end(), r));\n *std::back_inserter(out) = sample_triangle_uniform(*boost::begin(ring), *(boost::begin(ring)+t), *(boost::begin(ring)+t+1),gen);\n }\n}\n", "meta": {"hexsha": "fc5cd80b8793bc8e30e7d698b6f7c596842813e6", "size": 2075, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "convex-polygon-sampler.hpp", "max_stars_repo_name": "tinko92/boost_geometry_GSoC_2019_project_3_4_test", "max_stars_repo_head_hexsha": "3dc8d6e5282fa2f7cc501b3f5025ef2ccfec4637", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "convex-polygon-sampler.hpp", "max_issues_repo_name": "tinko92/boost_geometry_GSoC_2019_project_3_4_test", "max_issues_repo_head_hexsha": "3dc8d6e5282fa2f7cc501b3f5025ef2ccfec4637", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "convex-polygon-sampler.hpp", "max_forks_repo_name": "tinko92/boost_geometry_GSoC_2019_project_3_4_test", "max_forks_repo_head_hexsha": "3dc8d6e5282fa2f7cc501b3f5025ef2ccfec4637", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0163934426, "max_line_length": 152, "alphanum_fraction": 0.6597590361, "num_tokens": 583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7533904473770239}} {"text": "/*\n * COPYRIGHT AND PERMISSION NOTICE\n * Penn Software MSCKF_VIO\n * Copyright (C) 2017 The Trustees of the University of Pennsylvania\n * All rights reserved.\n */\n\n// The original file belongs to MSCKF_VIO (https://github.com/KumarRobotics/msckf_vio/)\n// Some changes have been made to use it in orcvio\n\n#ifndef MATH_UTILS_HPP\n#define MATH_UTILS_HPP\n\n#include \n#include \n#include \n\nnamespace orcvio {\n\n/*\n * @brief Create a skew-symmetric matrix from a 3-element vector.\n * @note Performs the operation:\n * w -> [ 0 -w3 w2]\n * [ w3 0 -w1]\n * [-w2 w1 0]\n */\ninline Eigen::Matrix3d skewSymmetric(const Eigen::Vector3d& w) {\n Eigen::Matrix3d w_hat;\n w_hat(0, 0) = 0;\n w_hat(0, 1) = -w(2);\n w_hat(0, 2) = w(1);\n w_hat(1, 0) = w(2);\n w_hat(1, 1) = 0;\n w_hat(1, 2) = -w(0);\n w_hat(2, 0) = -w(1);\n w_hat(2, 1) = w(0);\n w_hat(2, 2) = 0;\n return w_hat;\n}\n// /**\n// * @brief Skew-symmetric matrix from a given 3x1 vector\n// *\n// * This is based on equation 6 in [Indirect Kalman Filter for 3D Attitude Estimation](http://mars.cs.umn.edu/tr/reports/Trawny05b.pdf):\n// * \\f{align*}{\n// * \\lfloor\\mathbf{v}\\times\\rfloor =\n// * \\begin{bmatrix}\n// * 0 & -v_3 & v_2 \\\\ v_3 & 0 & -v_1 \\\\ -v_2 & v_1 & 0\n// * \\end{bmatrix}\n// * @f}\n// *\n// * @param[in] w 3x1 vector to be made a skew-symmetric\n// * @return 3x3 skew-symmetric matrix\n// */\n// template\n// Eigen::Matrix skewSymmetric(const Eigen::MatrixBase &w) {\n// static_assert(Der::RowsAtCompileTime == 3, \"3 vector\");\n// static_assert(Der::ColsAtCompileTime == 1, \"a vector\");\n// Eigen::Matrix w_x;\n// w_x << 0, -w(2, 0), w(1,0),\n// w(2, 0), 0, -w(0, 0),\n// -w(1, 0), w(0, 0), 0;\n// return w_x;\n// }\n\n/*\n * @brief Normalize the given quaternion to unit quaternion.\n */\ninline void quaternionNormalize(Eigen::Vector4d& q) {\n double norm = q.norm();\n q = q / norm;\n return;\n}\n\n/*\n * @brief Perform q1 * q2.\n * \n * Format of q1 and q2 is as [x,y,z,w]\n */\ninline Eigen::Vector4d quaternionMultiplication(\n const Eigen::Vector4d& q1,\n const Eigen::Vector4d& q2) {\n Eigen::Matrix4d L;\n\n // Hamilton\n L(0, 0) = q1(3); L(0, 1) = -q1(2); L(0, 2) = q1(1); L(0, 3) = q1(0);\n L(1, 0) = q1(2); L(1, 1) = q1(3); L(1, 2) = -q1(0); L(1, 3) = q1(1);\n L(2, 0) = -q1(1); L(2, 1) = q1(0); L(2, 2) = q1(3); L(2, 3) = q1(2);\n L(3, 0) = -q1(0); L(3, 1) = -q1(1); L(3, 2) = -q1(2); L(3, 3) = q1(3);\n\n Eigen::Vector4d q = L * q2;\n quaternionNormalize(q);\n return q;\n}\n\n/*\n * @brief Convert the vector part of a quaternion to a\n * full quaternion.\n * @note This function is useful to convert delta quaternion\n * which is usually a 3x1 vector to a full quaternion.\n * For more details, check Section 3.2 \"Kalman Filter Update\" in\n * \"Indirect Kalman Filter for 3D Attitude Estimation:\n * A Tutorial for quaternion Algebra\".\n */\ninline Eigen::Vector4d smallAngleQuaternion(\n const Eigen::Vector3d& dtheta) {\n\n Eigen::Vector3d dq = dtheta / 2.0;\n Eigen::Vector4d q;\n double dq_square_norm = dq.squaredNorm();\n\n if (dq_square_norm <= 1) {\n q.head<3>() = dq;\n q(3) = std::sqrt(1-dq_square_norm);\n } else {\n q.head<3>() = dq;\n q(3) = 1;\n q = q / std::sqrt(1+dq_square_norm);\n }\n\n return q;\n}\n\n/*\n * @brief Convert the vector part of a quaternion to a\n * full quaternion.\n * @note This function is useful to convert delta quaternion\n * which is usually a 3x1 vector to a full quaternion.\n * For more details, check Section 3.2 \"Kalman Filter Update\" in\n * \"Indirect Kalman Filter for 3D Attitude Estimation:\n * A Tutorial for quaternion Algebra\".\n */\ninline Eigen::Quaterniond getSmallAngleQuaternion(\n const Eigen::Vector3d& dtheta) {\n\n Eigen::Vector3d dq = dtheta / 2.0;\n Eigen::Quaterniond q;\n double dq_square_norm = dq.squaredNorm();\n\n if (dq_square_norm <= 1) {\n q.x() = dq(0);\n q.y() = dq(1);\n q.z() = dq(2);\n q.w() = std::sqrt(1-dq_square_norm);\n } else {\n q.x() = dq(0);\n q.y() = dq(1);\n q.z() = dq(2);\n q.w() = 1;\n q.normalize();\n }\n\n return q;\n}\n\n/*\n * @brief Convert a quaternion to the corresponding rotation matrix\n * @note Pay attention to the convention used. The function follows the\n * conversion in \"Indirect Kalman Filter for 3D Attitude Estimation:\n * A Tutorial for Quaternion Algebra\", Equation (78).\n *\n * The input quaternion should be in the form\n * [q1, q2, q3, q4(scalar)]^T\n */\ninline Eigen::Matrix3d quaternionToRotation(\n const Eigen::Vector4d& q) {\n // Hamilton\n const double& qw = q(3);\n const double& qx = q(0);\n const double& qy = q(1);\n const double& qz = q(2);\n Eigen::Matrix3d R;\n R(0, 0) = 1-2*(qy*qy+qz*qz); R(0, 1) = 2*(qx*qy-qw*qz); R(0, 2) = 2*(qx*qz+qw*qy);\n R(1, 0) = 2*(qx*qy+qw*qz); R(1, 1) = 1-2*(qx*qx+qz*qz); R(1, 2) = 2*(qy*qz-qw*qx);\n R(2, 0) = 2*(qx*qz-qw*qy); R(2, 1) = 2*(qy*qz+qw*qx); R(2, 2) = 1-2*(qx*qx+qy*qy);\n\n return R;\n}\n\n/*\n * @brief Convert a rotation matrix to a quaternion.\n * @note Pay attention to the convention used. The function follows the\n * conversion in \"Indirect Kalman Filter for 3D Attitude Estimation:\n * A Tutorial for Quaternion Algebra\", Equation (78).\n *\n * The input quaternion should be in the form\n * [q1, q2, q3, q4(scalar)]^T\n */\ninline Eigen::Vector4d rotationToQuaternion(\n const Eigen::Matrix3d& R) {\n Eigen::Vector4d score;\n score(0) = R(0, 0);\n score(1) = R(1, 1);\n score(2) = R(2, 2);\n score(3) = R.trace();\n\n int max_row = 0, max_col = 0;\n score.maxCoeff(&max_row, &max_col);\n\n Eigen::Vector4d q = Eigen::Vector4d::Zero();\n\n // Hamilton\n if (max_row == 0) {\n q(0) = std::sqrt(1+2*R(0, 0)-R.trace()) / 2.0;\n q(1) = (R(0, 1)+R(1, 0)) / (4*q(0));\n q(2) = (R(0, 2)+R(2, 0)) / (4*q(0));\n q(3) = (R(2, 1)-R(1, 2)) / (4*q(0));\n } else if (max_row == 1) {\n q(1) = std::sqrt(1+2*R(1, 1)-R.trace()) / 2.0;\n q(0) = (R(0, 1)+R(1, 0)) / (4*q(1));\n q(2) = (R(1, 2)+R(2, 1)) / (4*q(1));\n q(3) = (R(0, 2)-R(2, 0)) / (4*q(1));\n } else if (max_row == 2) {\n q(2) = std::sqrt(1+2*R(2, 2)-R.trace()) / 2.0;\n q(0) = (R(0, 2)+R(2, 0)) / (4*q(2));\n q(1) = (R(1, 2)+R(2, 1)) / (4*q(2));\n q(3) = (R(1, 0)-R(0, 1)) / (4*q(2));\n } else {\n q(3) = std::sqrt(1+R.trace()) / 2.0;\n q(0) = (R(2, 1)-R(1, 2)) / (4*q(3));\n q(1) = (R(0, 2)-R(2, 0)) / (4*q(3));\n q(2) = (R(1, 0)-R(0, 1)) / (4*q(3));\n }\n\n if (q(3) < 0) q = -q;\n quaternionNormalize(q);\n return q;\n}\n\ninline Eigen::Matrix3d Hl_operator(const Eigen::Vector3d& gyro) {\n\n double gyro_norm = gyro.norm();\n\n Eigen::Matrix3d term1 = 0.5 * Eigen::Matrix3d::Identity();\n\n // handle the case when the input is exactly 0 \n if (gyro_norm == 0)\n {\n return term1;\n }\n\n Eigen::Matrix3d term2 = ((gyro_norm - sin(gyro_norm)) / pow(gyro_norm, 3)) * skewSymmetric(gyro);\n Eigen::Matrix3d term3 = ((2*(cos(gyro_norm) - 1) + pow(gyro_norm, 2)) / (2*pow(gyro_norm, 4))) * (skewSymmetric(gyro) * skewSymmetric(gyro));\n\n Eigen::Matrix3d Hl = term1 + term2 + term3; \n \n return Hl;\n\n}\n\ninline Eigen::Matrix3d Jl_operator(const Eigen::Vector3d& gyro) {\n\n double gyro_norm = gyro.norm();\n\n Eigen::Matrix3d term1 = Eigen::Matrix3d::Identity();\n\n // handle the case when the input is exactly 0 \n if (gyro_norm == 0)\n {\n return term1;\n }\n\n Eigen::Matrix3d term2 = ((1 - cos(gyro_norm)) / pow(gyro_norm, 2)) * skewSymmetric(gyro);\n Eigen::Matrix3d term3 = ((gyro_norm - sin(gyro_norm)) / pow(gyro_norm, 3)) * skewSymmetric(gyro) * skewSymmetric(gyro);\n\n Eigen::Matrix3d Jl = term1 + term2 + term3; \n \n return Jl;\n \n}\n\ninline Eigen::Matrix3d Sigma3_operator(const Eigen::Vector3d& gyro_hat, const Eigen::Matrix3d& Sigma0, const double& dt) {\n\n double gyro_norm = gyro_hat.norm();\n\n Eigen::Matrix3d term1 = (1.0 / 6.0) * Eigen::Matrix3d::Identity() * pow(dt, 3);\n\n // handle the case when the input is exactly 0 \n if (gyro_norm == 0)\n {\n return term1;\n }\n\n Eigen::Matrix3d Theta_theta = -skewSymmetric(gyro_hat); \n \n Eigen::Matrix3d term2 = Theta_theta / pow(gyro_norm, 4);\n Eigen::Matrix3d term3 = Sigma0 - Eigen::Matrix3d::Identity() - Theta_theta * dt - 0.5 * Theta_theta * Theta_theta * pow(dt, 2) - (1.0 / 6.0) * Theta_theta * Theta_theta * Theta_theta * pow(dt, 3);\n\n Eigen::Matrix3d Sigma3 = term1 + term2 * term3; \n \n return Sigma3;\n\n}\n\n/*\n * @brief Inverse a Hamilton quaternion \n */\ninline Eigen::Vector4d inverseQuaternion(\n const Eigen::Vector4d& quat) {\n\n Eigen::Vector4d q_inv;\n\n Eigen::Quaterniond quat_Q = Eigen::Quaterniond(quat);\n q_inv = quat_Q.inverse().coeffs();\n\n return q_inv;\n}\n\ninline bool nullspace_project_inplace_svd(Eigen::MatrixXd &H_f, Eigen::MatrixXd &H_x, Eigen::VectorXd &res) \n{\n\n bool nullspace_trick_success_flag = true;\n\n if (H_f.rows() <= H_f.cols())\n {\n // insufficient residuals \n nullspace_trick_success_flag = false; \n }\n else \n {\n\n // Project the residual and Jacobians onto the nullspace of H_f.\n Eigen::JacobiSVD svd_helper(H_f, Eigen::ComputeFullU | Eigen::ComputeThinV);\n Eigen::MatrixXd A = svd_helper.matrixU().rightCols(\n H_f.rows() - H_f.cols());\n\n H_x = (A.transpose() * H_x).eval(); \n res = (A.transpose() * res).eval();\n\n }\n\n return nullspace_trick_success_flag; \n\n}\n\n// ref https://github.com/rpng/open_vins/blob/e169a77906941d662597bc83c8552e28b9a404f4/ov_msckf/src/update/UpdaterHelper.cpp\ninline bool nullspace_project_inplace_qr(Eigen::MatrixXd &H_f, Eigen::MatrixXd &H_x, Eigen::VectorXd &res) {\n\n bool nullspace_trick_success_flag = true; \n\n if (H_f.rows()-H_f.cols() <= 0)\n {\n // insufficient residuals \n nullspace_trick_success_flag = false;\n }\n else \n {\n\n // ref https://docs.openvins.com/update-null.html\n Eigen::ColPivHouseholderQR qr(H_f.rows(), H_f.cols());\n qr.compute(H_f);\n Eigen::MatrixXd Q = qr.householderQ();\n Eigen::MatrixXd Q1 = Q.block(0,0,H_f.rows(),H_f.cols());\n Eigen::MatrixXd Q2 = Q.block(0,H_f.cols(),H_f.rows(),H_f.rows()-H_f.cols());\n\n H_x = (Q2.transpose() * H_x).eval();\n res = (Q2.transpose() * res).eval();\n\n // Sanity check\n assert(H_x.rows()==res.rows());\n\n }\n\n return nullspace_trick_success_flag;\n\n}\n\ninline Eigen::Vector4d unnormalize_bbox(const Eigen::Vector4d& bbox, const Eigen::Matrix3d& K) {\n Eigen::Vector4d nbbox;\n nbbox.head<2>() = K.block<2,2>(0,0) * bbox.head<2>() + K.topRightCorner<2,1>();\n nbbox.tail<2>() = K.block<2,2>(0,0) * bbox.tail<2>() + K.topRightCorner<2,1>();\n return nbbox;\n}\n\ninline Eigen::Vector4d normalize_bbox(const Eigen::Vector4d& bbox, const Eigen::Matrix3d& K) {\n\n // bbox format is \n // bbox.xmin, bbox.ymin, bbox.xmax, bbox.ymax\n\n Eigen::Vector4d nbbox;\n\n // for x \n nbbox(0) = (bbox(0) - K(0,2)) / K(0,0);\n nbbox(2) = (bbox(2) - K(0,2)) / K(0,0);\n\n // for y \n nbbox(1) = (bbox(1) - K(1,2)) / K(1,1);\n nbbox(3) = (bbox(3) - K(1,2)) / K(1,1);\n\n return nbbox;\n}\n\n// ref https://eigen.tuxfamily.org/bz/show_bug.cgi?id=448\ntemplate\ninline bool is_finite(const Eigen::MatrixBase& x)\n{\n\treturn ( (x - x).array() == (x - x).array()).all();\n}\n\ntemplate\ninline bool check_nan(const Eigen::MatrixBase& x)\n{\n // returns false if there is nan \n // since nan does not equal to itself \n\treturn ((x.array() == x.array())).all();\n}\n\n} // end namespace orcvio\n\n#endif // MATH_UTILS_HPP\n", "meta": {"hexsha": "e79bd7aa5389735ffb9582ae1345ff93bd36a632", "size": 11643, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/orcvio/utils/math_utils.hpp", "max_stars_repo_name": "shanmo/OrcVIO-Object-Mapping", "max_stars_repo_head_hexsha": "e5337a56da72b23ebf5c9d9f87534fe2edc9c54c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-14T03:31:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-14T03:31:16.000Z", "max_issues_repo_path": "include/orcvio/utils/math_utils.hpp", "max_issues_repo_name": "shanmo/OrcVIO-Object-Mapping", "max_issues_repo_head_hexsha": "e5337a56da72b23ebf5c9d9f87534fe2edc9c54c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/orcvio/utils/math_utils.hpp", "max_forks_repo_name": "shanmo/OrcVIO-Object-Mapping", "max_forks_repo_head_hexsha": "e5337a56da72b23ebf5c9d9f87534fe2edc9c54c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3975609756, "max_line_length": 198, "alphanum_fraction": 0.5977840763, "num_tokens": 4235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.753291496791634}} {"text": "// Copyright Paul A. 2007, 2010\n// Copyright John Maddock 2006\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Simple example of computing probabilities and quantiles for\n// a Bernoulli random variable representing the flipping of a coin.\n\n// http://mathworld.wolfram.com/CoinTossing.html\n// http://en.wikipedia.org/wiki/Bernoulli_trial\n// Weisstein, Eric W. \"Dice.\" From MathWorld--A Wolfram Web Resource.\n// http://mathworld.wolfram.com/Dice.html\n// http://en.wikipedia.org/wiki/Bernoulli_distribution\n// http://mathworld.wolfram.com/BernoulliDistribution.html\n//\n// An idealized coin consists of a circular disk of zero thickness which,\n// when thrown in the air and allowed to fall, will rest with either side face up\n// (\"heads\" H or \"tails\" T) with equal probability. A coin is therefore a two-sided die.\n// Despite slight differences between the sides and nonzero thickness of actual coins,\n// the distribution of their tosses makes a good approximation to a p==1/2 Bernoulli distribution.\n\n//[binomial_coinflip_example1\n\n/*`An example of a [@http://en.wikipedia.org/wiki/Bernoulli_process Bernoulli process]\nis coin flipping.\nA variable in such a sequence may be called a Bernoulli variable.\n\nThis example shows using the Binomial distribution to predict the probability\nof heads and tails when throwing a coin.\n\nThe number of correct answers (say heads),\nX, is distributed as a binomial random variable\nwith binomial distribution parameters number of trials (flips) n = 10 and probability (success_fraction) of getting a head p = 0.5 (a 'fair' coin).\n\n(Our coin is assumed fair, but we could easily change the success_fraction parameter p\nfrom 0.5 to some other value to simulate an unfair coin,\nsay 0.6 for one with chewing gum on the tail,\nso it is more likely to fall tails down and heads up).\n\nFirst we need some includes and using statements to be able to use the binomial distribution, some std input and output, and get started:\n*/\n\n#include \n using boost::math::binomial;\n\n#include \n using std::cout; using std::endl; using std::left;\n#include \n using std::setw;\n\nint main()\n{\n cout << \"Using Binomial distribution to predict how many heads and tails.\" << endl;\n try\n {\n/*`\nSee note [link coinflip_eg_catch with the catch block]\nabout why a try and catch block is always a good idea.\n\nFirst, construct a binomial distribution with parameters success_fraction\n1/2, and how many flips.\n*/\n const double success_fraction = 0.5; // = 50% = 1/2 for a 'fair' coin.\n int flips = 10;\n binomial flip(flips, success_fraction);\n\n cout.precision(4);\n/*`\n Then some examples of using Binomial moments (and echoing the parameters).\n*/\n cout << \"From \" << flips << \" one can expect to get on average \"\n << mean(flip) << \" heads (or tails).\" << endl;\n cout << \"Mode is \" << mode(flip) << endl;\n cout << \"Standard deviation is \" << standard_deviation(flip) << endl;\n cout << \"So about 2/3 will lie within 1 standard deviation and get between \"\n << ceil(mean(flip) - standard_deviation(flip)) << \" and \"\n << floor(mean(flip) + standard_deviation(flip)) << \" correct.\" << endl;\n cout << \"Skewness is \" << skewness(flip) << endl;\n // Skewness of binomial distributions is only zero (symmetrical)\n // if success_fraction is exactly one half,\n // for example, when flipping 'fair' coins.\n cout << \"Skewness if success_fraction is \" << flip.success_fraction()\n << \" is \" << skewness(flip) << endl << endl; // Expect zero for a 'fair' coin.\n/*`\nNow we show a variety of predictions on the probability of heads:\n*/\n cout << \"For \" << flip.trials() << \" coin flips: \" << endl;\n cout << \"Probability of getting no heads is \" << pdf(flip, 0) << endl;\n cout << \"Probability of getting at least one head is \" << 1. - pdf(flip, 0) << endl;\n/*`\nWhen we want to calculate the probability for a range or values we can sum the PDF's:\n*/\n cout << \"Probability of getting 0 or 1 heads is \"\n << pdf(flip, 0) + pdf(flip, 1) << endl; // sum of exactly == probabilities\n/*`\nOr we can use the cdf.\n*/\n cout << \"Probability of getting 0 or 1 (<= 1) heads is \" << cdf(flip, 1) << endl;\n cout << \"Probability of getting 9 or 10 heads is \" << pdf(flip, 9) + pdf(flip, 10) << endl;\n/*`\nNote that using\n*/\n cout << \"Probability of getting 9 or 10 heads is \" << 1. - cdf(flip, 8) << endl;\n/*`\nis less accurate than using the complement\n*/\n cout << \"Probability of getting 9 or 10 heads is \" << cdf(complement(flip, 8)) << endl;\n/*`\nSince the subtraction may involve\n[@http://docs.sun.com/source/806-3568/ncg_goldberg.html cancellation error],\nwhere as `cdf(complement(flip, 8))`\ndoes not use such a subtraction internally, and so does not exhibit the problem.\n\nTo get the probability for a range of heads, we can either add the pdfs for each number of heads\n*/\n cout << \"Probability of between 4 and 6 heads (4 or 5 or 6) is \"\n // P(X == 4) + P(X == 5) + P(X == 6)\n << pdf(flip, 4) + pdf(flip, 5) + pdf(flip, 6) << endl;\n/*`\nBut this is probably less efficient than using the cdf\n*/\n cout << \"Probability of between 4 and 6 heads (4 or 5 or 6) is \"\n // P(X <= 6) - P(X <= 3) == P(X < 4)\n << cdf(flip, 6) - cdf(flip, 3) << endl;\n/*`\nCertainly for a bigger range like, 3 to 7\n*/\n cout << \"Probability of between 3 and 7 heads (3, 4, 5, 6 or 7) is \"\n // P(X <= 7) - P(X <= 2) == P(X < 3)\n << cdf(flip, 7) - cdf(flip, 2) << endl;\n cout << endl;\n\n/*`\nFinally, print two tables of probability for the /exactly/ and /at least/ a number of heads.\n*/\n // Print a table of probability for the exactly a number of heads.\n cout << \"Probability of getting exactly (==) heads\" << endl;\n for (int successes = 0; successes <= flips; successes++)\n { // Say success means getting a head (or equally success means getting a tail).\n double probability = pdf(flip, successes);\n cout << left << setw(2) << successes << \" \" << setw(10)\n << probability << \" or 1 in \" << 1. / probability\n << \", or \" << probability * 100. << \"%\" << endl;\n } // for i\n cout << endl;\n\n // Tabulate the probability of getting between zero heads and 0 upto 10 heads.\n cout << \"Probability of getting upto (<=) heads\" << endl;\n for (int successes = 0; successes <= flips; successes++)\n { // Say success means getting a head\n // (equally success could mean getting a tail).\n double probability = cdf(flip, successes); // P(X <= heads)\n cout << setw(2) << successes << \" \" << setw(10) << left\n << probability << \" or 1 in \" << 1. / probability << \", or \"\n << probability * 100. << \"%\"<< endl;\n } // for i\n/*`\nThe last (0 to 10 heads) must, of course, be 100% probability.\n*/\n double probability = 0.3;\n double q = quantile(flip, probability);\n std::cout << \"Quantile (flip, \" << probability << \") = \" << q << std::endl; // Quantile (flip, 0.3) = 3\n probability = 0.6;\n q = quantile(flip, probability);\n std::cout << \"Quantile (flip, \" << probability << \") = \" << q << std::endl; // Quantile (flip, 0.6) = 5\n }\n catch(const std::exception& e)\n {\n //\n /*`\n [#coinflip_eg_catch]\n It is always essential to include try & catch blocks because\n default policies are to throw exceptions on arguments that\n are out of domain or cause errors like numeric-overflow.\n\n Lacking try & catch blocks, the program will abort, whereas the\n message below from the thrown exception will give some helpful\n clues as to the cause of the problem.\n */\n std::cout <<\n \"\\n\"\"Message from thrown exception was:\\n \" << e.what() << std::endl;\n }\n//] [binomial_coinflip_example1]\n return 0;\n} // int main()\n\n// Output:\n\n//[binomial_coinflip_example_output\n/*`\n\n[pre\nUsing Binomial distribution to predict how many heads and tails.\nFrom 10 one can expect to get on average 5 heads (or tails).\nMode is 5\nStandard deviation is 1.581\nSo about 2/3 will lie within 1 standard deviation and get between 4 and 6 correct.\nSkewness is 0\nSkewness if success_fraction is 0.5 is 0\n\nFor 10 coin flips:\nProbability of getting no heads is 0.0009766\nProbability of getting at least one head is 0.999\nProbability of getting 0 or 1 heads is 0.01074\nProbability of getting 0 or 1 (<= 1) heads is 0.01074\nProbability of getting 9 or 10 heads is 0.01074\nProbability of getting 9 or 10 heads is 0.01074\nProbability of getting 9 or 10 heads is 0.01074\nProbability of between 4 and 6 heads (4 or 5 or 6) is 0.6562\nProbability of between 4 and 6 heads (4 or 5 or 6) is 0.6563\nProbability of between 3 and 7 heads (3, 4, 5, 6 or 7) is 0.8906\n\nProbability of getting exactly (==) heads\n0 0.0009766 or 1 in 1024, or 0.09766%\n1 0.009766 or 1 in 102.4, or 0.9766%\n2 0.04395 or 1 in 22.76, or 4.395%\n3 0.1172 or 1 in 8.533, or 11.72%\n4 0.2051 or 1 in 4.876, or 20.51%\n5 0.2461 or 1 in 4.063, or 24.61%\n6 0.2051 or 1 in 4.876, or 20.51%\n7 0.1172 or 1 in 8.533, or 11.72%\n8 0.04395 or 1 in 22.76, or 4.395%\n9 0.009766 or 1 in 102.4, or 0.9766%\n10 0.0009766 or 1 in 1024, or 0.09766%\n\nProbability of getting upto (<=) heads\n0 0.0009766 or 1 in 1024, or 0.09766%\n1 0.01074 or 1 in 93.09, or 1.074%\n2 0.05469 or 1 in 18.29, or 5.469%\n3 0.1719 or 1 in 5.818, or 17.19%\n4 0.377 or 1 in 2.653, or 37.7%\n5 0.623 or 1 in 1.605, or 62.3%\n6 0.8281 or 1 in 1.208, or 82.81%\n7 0.9453 or 1 in 1.058, or 94.53%\n8 0.9893 or 1 in 1.011, or 98.93%\n9 0.999 or 1 in 1.001, or 99.9%\n10 1 or 1 in 1, or 100%\n]\n*/\n//][/binomial_coinflip_example_output]\n", "meta": {"hexsha": "14940cb94d71cb5fbdcdfddff0635fb1cc78db7b", "size": 9914, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/binomial_coinflip_example.cpp", "max_stars_repo_name": "btzy/boost-1.72.0-mirror", "max_stars_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-01T03:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-01T03:04:05.000Z", "max_issues_repo_path": "libs/math/example/binomial_coinflip_example.cpp", "max_issues_repo_name": "btzy/boost-1.72.0-mirror", "max_issues_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/example/binomial_coinflip_example.cpp", "max_forks_repo_name": "btzy/boost-1.72.0-mirror", "max_forks_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.631147541, "max_line_length": 147, "alphanum_fraction": 0.6508977204, "num_tokens": 3007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029117, "lm_q2_score": 0.870597273444551, "lm_q1q2_score": 0.7532617362868695}} {"text": "#include \n#include\n#include \n#include \nusing namespace std;\n\n\n\n\n\nclass RBFN {\n\n private:\n double epseta = 0.5 ; //learning rate\n double seta = 0.0005; // seta\n int xn; //2\n int k; //5\n Eigen::MatrixXd b;\n Eigen::MatrixXd last_b ;\n Eigen::MatrixXd last_last_b ;\n \n Eigen::MatrixXd c;\n Eigen::MatrixXd last_c ;\n Eigen::MatrixXd last_last_c ;\n\n Eigen::MatrixXd w ;\n Eigen::MatrixXd last_w ;\n Eigen::MatrixXd last_last_w ;\n\n \n Eigen::MatrixXd dk;\n \n Eigen::MatrixXd s_input;\n double Derivative_teacher_E;\n\n static double gaussian(double d, double b) {\n // exp( -(d^2)/2*s^2 )\n double tmp = - (d) / (2 * b*b);\n double ret = std::exp(tmp);\n return ret;\n }\n\n\n public:\n RBFN(int xn1, int k1) {\n xn = xn1;\n k = k1;\n init();\n \n\n }\n\n void init() {\n \n b = Eigen::MatrixXd::Random(k, 1);\n last_b = Eigen::MatrixXd::Random(k, 1);\n last_last_b = Eigen::MatrixXd::Random(k, 1);\n \n c = Eigen::MatrixXd::Random(k, xn);\n last_c = Eigen::MatrixXd::Random(k, xn);\n last_last_c = Eigen::MatrixXd::Random(k, xn);\n\n w = Eigen::MatrixXd::Random(k, 1);\n last_w = Eigen::MatrixXd::Random(k, 1);\n last_last_w = Eigen::MatrixXd::Random(k, 1);\n\n \n dk = Eigen::MatrixXd::Random(k, 1);\n cout << \"w: \" << w <\n#include \n#include \n#include \n#include \n\nMultivariateNormal::MultivariateNormal(const Eigen::MatrixXd& data,\n const Eigen::VectorXd& mu0,\n const Eigen::MatrixXd& S0,\n double k0,\n double v0)\n : LikelihoodFcn(data),\n phyper_(mu0, S0, k0, v0)\n{\n}\n\n// Ref. https://www.cs.ubc.ca/~murphyk/Papers/bayesGauss.pdf page 21: Marginal likelihood\ndouble MultivariateNormal::compute_marginal_log_likelihood(const std::set& members) const\n{\n NIWHyperParam hpost = get_posterior_hyperparameters(members);\n\n double marginal_ll = - ( static_cast(members.size() * data_dimension()) / 2.0) * std::log( boost::math::constants::pi() );\n marginal_ll += multivariate_log_gamma_ratio(hpost.v_/2.0, phyper_.v_/2.0, data_dimension() );\n marginal_ll += (phyper_.v_ / 2.0) * std::log( phyper_.S_.determinant() ) - (hpost.v_ / 2.0) * std::log( hpost.S_.determinant() );\n marginal_ll += (static_cast( data_dimension() ) / 2.0) * ( std::log(phyper_.k_) - std::log(hpost.k_) );\n\n return marginal_ll;\n}\n\nNIWHyperParam MultivariateNormal::get_posterior_hyperparameters(const std::set& members) const\n{\n // Murphy: Machine learning - a probabilistic perspective\n // Sect. 4.6.3.3\n const double num_data = static_cast( members.size() );\n NIWHyperParam hpost(phyper_);\n hpost.mu_ = ( phyper_.k_ / ( phyper_.k_ + num_data ) ) * phyper_.mu_ + (num_data / ( phyper_.k_ + num_data ) ) * sample_mean(members);\n hpost.k_ += num_data;\n hpost.v_ += num_data;\n hpost.S_ += sample_uncentered_sum_of_squares_matrix(members) + phyper_.k_ * ( phyper_.mu_ * phyper_.mu_.transpose() ) - hpost.k_ * ( hpost.mu_ * hpost.mu_.transpose() );\n\n return hpost;\n}\n\ndouble MultivariateNormal::multivariate_log_gamma_ratio(double a, double b, std::size_t d)\n{\n double y = 0.0;\n for ( std::size_t i = 1; i <= d; ++i)\n {\n const double d = (1.0 - static_cast(i)) / 2.0;\n try\n {\n //y += std::log( boost::math::tgamma_ratio(a+d, b+d) );\n y += std::lgamma(a+d) - std::lgamma(b+d);\n }\n catch (...)\n {\n std::cout << \"Failure with a+d = \" << a+d << \" and b+d = \" << b + d << \" (d = \" << d << \")\\n\";\n throw;\n }\n }\n\n return y;\n}\n", "meta": {"hexsha": "9b8153861327c4790eb28e7ce29d4fad680e98e8", "size": 2590, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MultivariateNormal.cpp", "max_stars_repo_name": "laurimi/ddcrp-gibbs", "max_stars_repo_head_hexsha": "bcb2374b8d09ad9358161c6a7e5c6de5eedfdba0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-09-21T13:46:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-27T08:58:12.000Z", "max_issues_repo_path": "src/MultivariateNormal.cpp", "max_issues_repo_name": "hyc9527/ddcrp-gibbs", "max_issues_repo_head_hexsha": "bcb2374b8d09ad9358161c6a7e5c6de5eedfdba0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-10-20T19:04:18.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-20T19:04:18.000Z", "max_forks_repo_path": "src/MultivariateNormal.cpp", "max_forks_repo_name": "hyc9527/ddcrp-gibbs", "max_forks_repo_head_hexsha": "bcb2374b8d09ad9358161c6a7e5c6de5eedfdba0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-09-21T13:48:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T12:53:51.000Z", "avg_line_length": 39.8461538462, "max_line_length": 173, "alphanum_fraction": 0.6019305019, "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.753215368880747}} {"text": "//\n// main.cpp\n// 5 - Normal Distribution\n//\n// Created by Zhehao Li on 2020/4/16.\n// Copyright © 2020 Zhehao Li. All rights reserved.\n//\n\n#include \n#include \n#include // For non-member functions of distributions\n\n#include \n#include \nusing namespace std;\n\nint main(int argc, const char * argv[]) {\n // Don't forget to tell compiler which namespace\n using namespace boost::math;\n\n // 1. Create normal distribution object\n normal_distribution<> myNormal(1.0, 10.0); // Default type is 'double'\n cout << \"Mean: \" << mean(myNormal) << \", standard deviation: \" << standard_deviation(myNormal) << endl;\n\n // 1.1 Distributional properties\n double x = 10.25;\n\n cout << \"pdf: \" << pdf(myNormal, x) << endl;\n cout << \"cdf: \" << cdf(myNormal, x) << endl;\n\n // 1.2 Choose another data type and now a N(0,1) variate\n normal_distribution myNormal2;\n cout << \"Mean: \" << mean(myNormal2) << \", standard deviation: \" << standard_deviation(myNormal2) << endl;\n\n cout << \"pdf: \" << pdf(myNormal2, x) << endl;\n cout << \"cdf: \" << cdf(myNormal2, x) << endl;\n\n // 1.3 Choose precision\n cout.precision(10); // Number of values behind the comma\n\n // 1.4 Other properties\n cout << \"\\n*** normal distribution ***: \\n\";\n cout << \"mean: \" << mean(myNormal) << endl;\n cout << \"variance: \" << variance(myNormal) << endl;\n cout << \"median: \" << median(myNormal) << endl;\n cout << \"mode: \" << mode(myNormal) << endl;\n cout << \"kurtosis excess: \" << kurtosis_excess(myNormal) << endl;\n cout << \"kurtosis: \" << kurtosis(myNormal) << endl;\n cout << \"characteristic function: \" << chf(myNormal, x) << endl;\n cout << \"hazard: \" << hazard(myNormal, x) << endl;\n\n // 2. Gamma distribution\n double alpha = 3.0; // Shape parameter, k\n double beta = 0.5; // Scale parameter, theta\n gamma_distribution myGamma(alpha, beta);\n\n double val = 13.0;\n cout << endl << \"pdf: \" << pdf(myGamma, val) << endl;\n cout << \"cdf: \" << cdf(myGamma, val) << endl;\n\n vector pdfList;\n vector cdfList;\n\n double start = 0.0;\n double end = 10.0;\n long N = 30; // Number of subdivisions\n\n val = 0.0;\n double h = (end - start) / double(N);\n\n for (long j = 1; j <= N; ++j){\n pdfList.push_back(pdf(myGamma, val));\n cdfList.push_back(cdf(myGamma, val));\n\n val += h;\n }\n\n for (long j = 0; j < pdfList.size(); ++j){\n cout << pdfList[j] << \", \";\n }\n\n cout << \"***\" << endl;\n\n for (long j = 0; j < cdfList.size(); ++j){\n cout << cdfList[j] << \", \";\n }\n \n return 0;\n}\n", "meta": {"hexsha": "58cdebe2e3ddd314578c86c18beb2a03d40075ae", "size": 2826, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Level_8/V. C++ Boost/5 - Normal Distribution/5 - Normal Distribution/main.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_8/V. C++ Boost/5 - Normal Distribution/5 - Normal Distribution/main.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_8/V. C++ Boost/5 - Normal Distribution/5 - Normal Distribution/main.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": 31.4, "max_line_length": 109, "alphanum_fraction": 0.5661712668, "num_tokens": 817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693631290971, "lm_q2_score": 0.793105953629227, "lm_q1q2_score": 0.7531884258769632}} {"text": "/**\n * @file linquadlagrfe.cc\n * @brief Creates convergence plots for experiment 3.2.3.7 and 3.2.3.8\n * @author Tobias Rohner\n * @date April 2020\n * @copyright MIT License\n */\n\n#define _USE_MATH_DEFINES\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace po = boost::program_options;\n\n/**\n * @brief Solves the Poisson problem on a given mesh\n * @param mesh The mesh on which to solve the PDE\n * @param fe_space The Finite Element Space to use\n * @returns The dof vector corresponding to the solution of the PDE\n *\n * The Dirichlet boundary conditions are set to zero and the load is given by\n * \\f[\n f(x) = 2\\pi^2\\sin(\\pi x_1)\\sin\\pi x_2)\n \\f]\n */\nEigen::VectorXd solvePoisson(\n const std::shared_ptr &mesh,\n const std::shared_ptr>\n &fe_space) {\n // Define the load function of the manufactured solution\n const auto load = [](const Eigen::Vector2d &x) -> double {\n return 2 * M_PI * M_PI * std::sin(M_PI * x[0]) * std::sin(M_PI * x[1]);\n };\n const lf::mesh::utils::MeshFunctionGlobal mf_load(load);\n\n // Intialize the matrix and vector providers\n const lf::mesh::utils::MeshFunctionConstant mf_alpha(1);\n const lf::mesh::utils::MeshFunctionConstant mf_gamma(0);\n lf::uscalfe::ReactionDiffusionElementMatrixProvider element_matrix_provider(\n fe_space, mf_alpha, mf_gamma);\n lf::uscalfe::ScalarLoadElementVectorProvider element_vector_provider(\n fe_space, mf_load,\n {{lf::base::RefEl::kTria(),\n lf::quad::make_QuadRule(lf::base::RefEl::kTria(), 6)},\n {lf::base::RefEl::kQuad(),\n lf::quad::make_QuadRule(lf::base::RefEl::kQuad(), 6)}});\n\n // Assemble the system matrix and right hand side\n const lf::assemble::DofHandler &dofh = fe_space->LocGlobMap();\n lf::assemble::COOMatrix A_COO(dofh.NumDofs(), dofh.NumDofs());\n Eigen::VectorXd rhs = Eigen::VectorXd::Zero(dofh.NumDofs());\n std::cout << \"\\t\\t> Assembling System Matrix\" << std::endl;\n lf::assemble::AssembleMatrixLocally(0, dofh, dofh, element_matrix_provider,\n A_COO);\n std::cout << \"\\t\\t> Assembling right Hand Side\" << std::endl;\n lf::assemble::AssembleVectorLocally(0, dofh, element_vector_provider, rhs);\n\n // Enforce zero dirichlet boundary conditions\n std::cout << \"\\t\\t> Enforcing Boundary Conditions\" << std::endl;\n const auto boundary = lf::mesh::utils::flagEntitiesOnBoundary(mesh);\n const auto selector = [&](unsigned int idx) -> std::pair {\n return {boundary(dofh.Entity(idx)), 0};\n };\n lf::assemble::FixFlaggedSolutionComponents(selector, A_COO, rhs);\n\n // Solve the LSE using the cholesky decomposition\n std::cout << \"\\t\\t> Solving LSE\" << std::endl;\n Eigen::SparseMatrix A = A_COO.makeSparse();\n Eigen::SimplicialLDLT> solver(A);\n Eigen::VectorXd solution = solver.solve(rhs);\n\n // Return the resulting dof vector\n return solution;\n}\n\nint main(int argc, char *argv[]) {\n const int num_meshes = 7;\n\n po::options_description desc(\"allowed options\");\n desc.add_options()(\"output,o\", po::value(),\n \"Name of the output file\");\n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n if (vm.count(\"output\") == 0) {\n std::cout << desc << std::endl;\n exit(1);\n }\n const std::string output_file = vm[\"output\"].as();\n\n // The analytic solution\n const auto u = [](const Eigen::VectorXd &x) -> double {\n return std::sin(M_PI * x[0]) * std::sin(M_PI * x[1]);\n };\n const lf::mesh::utils::MeshFunctionGlobal mf_u(u);\n // The gradient of the analytic solution\n const auto u_grad = [](const Eigen::Vector2d &x) -> Eigen::Vector2d {\n Eigen::Vector2d grad;\n grad[0] = M_PI * std::cos(M_PI * x[0]) * std::sin(M_PI * x[1]);\n grad[1] = M_PI * std::sin(M_PI * x[0]) * std::cos(M_PI * x[1]);\n return grad;\n };\n const lf::mesh::utils::MeshFunctionGlobal mf_u_grad(u_grad);\n\n const std::filesystem::path here = __FILE__;\n const std::filesystem::path mesh_folder = here.parent_path() / \"meshes\";\n Eigen::MatrixXd results(num_meshes, 7);\n for (int mesh_idx = 0; mesh_idx < num_meshes; ++mesh_idx) {\n std::cout << \"> Mesh Nr. \" << mesh_idx << std::endl;\n\n // Load the mesh\n std::cout << \"\\t> Loading Mesh\" << std::endl;\n const std::string mesh_name =\n \"unitsquare\" + std::to_string(mesh_idx) + \".msh\";\n const std::filesystem::path mesh_file = mesh_folder / mesh_name;\n auto factory = std::make_unique(2);\n const lf::io::GmshReader reader(std::move(factory), mesh_file.string());\n const auto mesh = reader.mesh();\n\n // Solve the problem with linear finite elements\n std::cout << \"\\t> Linear Lagrangian FE\";\n const auto fe_space_o1 =\n std::make_shared>(mesh);\n std::cout << \" (\" << fe_space_o1->LocGlobMap().NumDofs() << \" DOFs)\"\n << std::endl;\n const Eigen::VectorXd solution_o1 = solvePoisson(mesh, fe_space_o1);\n const lf::fe::MeshFunctionFE mf_o1(fe_space_o1,\n solution_o1);\n const lf::fe::MeshFunctionGradFE mf_grad_o1(fe_space_o1,\n solution_o1);\n\n // Solve the problem with quadratic finite elements\n std::cout << \"\\t> Quadratic Lagrangian FE\";\n const auto fe_space_o2 =\n std::make_shared>(mesh);\n std::cout << \" (\" << fe_space_o2->LocGlobMap().NumDofs() << \" DOFs)\"\n << std::endl;\n const Eigen::VectorXd solution_o2 = solvePoisson(mesh, fe_space_o2);\n const lf::fe::MeshFunctionFE mf_o2(fe_space_o2,\n solution_o2);\n const lf::fe::MeshFunctionGradFE mf_grad_o2(fe_space_o2,\n solution_o2);\n\n // Compute the H1 and L2 errors\n std::cout << \"\\t> Computing Error Norms\" << std::endl;\n const auto quadrule_provider = [](const lf::mesh::Entity &entity) {\n return lf::quad::make_QuadRule(entity.RefEl(), 6);\n };\n const double H1_err_o1 = std::sqrt(lf::fe::IntegrateMeshFunction(\n *mesh, lf::mesh::utils::squaredNorm(mf_grad_o1 - mf_u_grad),\n quadrule_provider));\n const double H1_err_o2 = std::sqrt(lf::fe::IntegrateMeshFunction(\n *mesh, lf::mesh::utils::squaredNorm(mf_grad_o2 - mf_u_grad),\n quadrule_provider));\n const double L2_err_o1 = std::sqrt(lf::fe::IntegrateMeshFunction(\n *mesh, lf::mesh::utils::squaredNorm(mf_o1 - mf_u), quadrule_provider));\n const double L2_err_o2 = std::sqrt(lf::fe::IntegrateMeshFunction(\n *mesh, lf::mesh::utils::squaredNorm(mf_o2 - mf_u), quadrule_provider));\n\n // Store the mesh width, the number of DOFs and the errors in the results\n // matrix\n results(mesh_idx, 0) = std::sqrt(1. / mesh->NumEntities(0));\n results(mesh_idx, 1) = fe_space_o1->LocGlobMap().NumDofs();\n results(mesh_idx, 2) = fe_space_o2->LocGlobMap().NumDofs();\n results(mesh_idx, 3) = H1_err_o1;\n results(mesh_idx, 4) = H1_err_o2;\n results(mesh_idx, 5) = L2_err_o1;\n results(mesh_idx, 6) = L2_err_o2;\n }\n\n // Output the resulting errors to a file\n const static Eigen::IOFormat CSVFormat(Eigen::StreamPrecision,\n Eigen::DontAlignCols, \", \", \"\\n\");\n std::ofstream file;\n file.open(output_file);\n file << results.format(CSVFormat);\n file.close();\n\n return 0;\n}\n", "meta": {"hexsha": "a04638f3b82c13c1e126b3a7319d60fd4a0d0372", "size": 8091, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/lecturedemos/convergencestudies/linquadlagrfe.cc", "max_stars_repo_name": "Fytch/lehrfempp", "max_stars_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2018-08-30T19:55:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T16:38:06.000Z", "max_issues_repo_path": "examples/lecturedemos/convergencestudies/linquadlagrfe.cc", "max_issues_repo_name": "Fytch/lehrfempp", "max_issues_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 151.0, "max_issues_repo_issues_event_min_datetime": "2018-05-27T13:01:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T14:50:50.000Z", "max_forks_repo_path": "examples/lecturedemos/convergencestudies/linquadlagrfe.cc", "max_forks_repo_name": "Fytch/lehrfempp", "max_forks_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2018-11-13T13:46:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T17:33:52.000Z", "avg_line_length": 40.6582914573, "max_line_length": 79, "alphanum_fraction": 0.6484983315, "num_tokens": 2287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7531220195894244}} {"text": "#include\n#include \n#include\n#include\n#include \n#include\n\n#define\tTOTAL_ITERATIONS\t50000\n\nusing Eigen::MatrixXd;\nusing namespace std;\n\n//helper function declaration:\nMatrixXd* read_matrix(string filename);\nvoid write_matrix(string filename, MatrixXd m);\nvoid write_vec(string filename, vector m);\n\n// MAIN PROGRAM\nint main(){\n string casename = \"A\";\n // import the data required from A,B and C files\n\n MatrixXd* data = read_matrix(\"Data_\"+ casename + \"_lab_2.csv\");\n\n double\tan,an1,fan,fpan, xi, yi;\n int\ti,j;\n\n an = 0.1;\t// initial guess of a\n vector v;\n v.push_back(an);\n for (j=0; j > rows; \n string line;\n while(myfile.good()){\n vector row;\n getline(myfile, line);\n // cout< m){\n ofstream(myfile);\n myfile.open(filename);\n for(int i=0; i\n#include \n#include \n\n#include \n#include \n#include \n\nusing std::vector;\n\nnamespace GRANSAC\n{\n\nclass Regression2D\n{\npublic:\n\n\tstatic void calculateLLS_QR(const std::vector &xv, const std::vector &yv, std::vector &coeff, int order)\n {\n\t\tEigen::MatrixXf A(xv.size(), order+1);\n\t\tEigen::VectorXf yv_mapped = Eigen::VectorXf::Map(&yv.front(), yv.size());\n\t\tEigen::VectorXf result;\n\n\t\tassert(xv.size() == yv.size());\n\t\tassert(xv.size() >= order+1);\n\n\t\t// create matrix\n\t\tfor (size_t i = 0; i < xv.size(); i++)\n\t\tfor (size_t j = 0; j < order+1; j++)\n\t\t\tA(i, j) = pow(xv.at(i), j);\n\n\t\t// solve for linear least squares fit\n\t\tresult = A.householderQr().solve(yv_mapped);\n\n\t\tcoeff.resize(order+1);\n\t\tfor (size_t i = 0; i < order+1; i++)\n\t\t\tcoeff[i] = result[i];\n\t}\n\n static void calculateLLS(const std::vector &xv, const std::vector &yv, std::vector &coeff, int order)\n {\n // faster but with larger condition number compared with QR method\n\t\tEigen::MatrixXf A(xv.size(), order+1);\n\t\tEigen::VectorXf yv_mapped = Eigen::VectorXf::Map(&yv.front(), yv.size());\n\t\tEigen::VectorXf result;\n\n\t\tassert(xv.size() == yv.size());\n\t\tassert(xv.size() >= order+1);\n\n\t\t// create matrix\n\t\tfor (size_t i = 0; i < xv.size(); i++)\n\t\tfor (size_t j = 0; j < order+1; j++)\n\t\t\tA(i, j) = pow(xv.at(i), j);\n\n\t\t// solve for linear least squares fit\n\t\tresult = (A.transpose() * A).ldlt().solve(A.transpose() * yv_mapped);\n\n\t\tcoeff.resize(order+1);\n\t\tfor (size_t i = 0; i < order+1; i++)\n\t\t\tcoeff[i] = result[i];\n\t}\n\n\tstatic void calculateLLS_L2(const std::vector &xv, const std::vector &yv, std::vector &coeff, int order, float r_term=0.0f)\n {\n // faster but with larger condition number compared with QR method\n\t\tEigen::MatrixXf A(xv.size(), order+1);\n\t\tEigen::VectorXf yv_mapped = Eigen::VectorXf::Map(&yv.front(), yv.size());\n\t\tEigen::VectorXf result;\n\n\t\tassert(xv.size() == yv.size());\n\t\tassert(xv.size() >= order+1);\n\n\t\t// create matrix\n\t\tfor (size_t i = 0; i < xv.size(); i++)\n\t\tfor (size_t j = 0; j < order+1; j++)\n\t\t\tA(i, j) = pow(xv.at(i), j);\n\n\t\t// solve for linear least squares fit\n\t\tresult = (A.transpose() * A + r_term * Eigen::MatrixXf::Identity(A.cols(), A.cols())).ldlt().solve(A.transpose() * yv_mapped);\n\n\t\tcoeff.resize(order+1);\n\t\tfor (size_t i = 0; i < order+1; i++)\n\t\t\tcoeff[i] = result[i];\n\t}\n\n\n};\n\n\n}\n", "meta": {"hexsha": "ba3dacd66759afbe5f6fa3e7daf411a13ade7daf", "size": 2452, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/regression2d.hpp", "max_stars_repo_name": "masszhou/GRANSAC", "max_stars_repo_head_hexsha": "10afa96d7c0bf50959186403d3830a0d197cf823", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/regression2d.hpp", "max_issues_repo_name": "masszhou/GRANSAC", "max_issues_repo_head_hexsha": "10afa96d7c0bf50959186403d3830a0d197cf823", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/regression2d.hpp", "max_forks_repo_name": "masszhou/GRANSAC", "max_forks_repo_head_hexsha": "10afa96d7c0bf50959186403d3830a0d197cf823", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3655913978, "max_line_length": 145, "alphanum_fraction": 0.6199021207, "num_tokens": 813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475762847495, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7529675622032057}} {"text": "#include \n#include \n// #include \n// #include \n#include \n#include \n\nusing namespace std;\n\ntypedef std::pair int_pair;\n\nclass Solution {\npublic:\n int maxPoints(vector>& points) {\n int n = points.size();\n int result = 0;\n // unordered_map > gradients;\n map gradients;\n for (int i = 0; i < n - result; ++i) {\n gradients.clear();\n int over = 1, vertical = 0, cur_max = 0;\n for (int j = i+1; j < n; ++j) {\n if (points[i][0] == points[j][0]) {\n if (points[i][1] == points[j][1]) over++;\n else if (++vertical > cur_max) cur_max = vertical;\n continue;\n }\n int dy = points[j][1] - points[i][1];\n int dx = points[j][0] - points[i][0];\n int div = __gcd(dy, dx);\n int_pair i_pair = {dy / div, dx / div};\n if (++gradients[i_pair] > cur_max) {\n cur_max = gradients[i_pair];\n }\n }\n result = max(result, cur_max + over);\n }\n return result;\n }\n};\n\nint main(int argc, char const *argv[])\n{\n vector> points = {{84,250},{0,0},{1,0},{0,-70},{0,-70},{1,-1},{21,10},{42,90},{-42,-230}};\n vector> points2 = {{0,0},{94911151,94911150},{94911152,94911151}};\n Solution s;\n cout<\n#include \n#include \n#include \"sophus/se3.hpp\"\n\n\ntypedef std::vector> TrajectoryType;\n\n\nstd::string estimated_file_path = \"estimated.txt\";\nstd::string groundtruth_file_path = \"groundtruth.txt\";\n\nTrajectoryType ReadTrajectory(std::string &file_path){\n std::fstream fin(file_path);\n TrajectoryType trajectory;\n double time, qx, qy, qz, qw, tx, ty, tz;\n\n if (!fin){\n std::cerr << \"cannot open file \" << file_path << \"!\" << std::endl;\n }\n\n while(!fin.eof()){\n fin >> time >> tx >> ty >> tz >> qx >> qy >> qz >> qw;\n\n Eigen::Quaterniond q(qx, qy, qz, qw);\n Eigen::Vector3d t(tx, ty, tz);\n Sophus::SE3d T(q, t);\n\n trajectory.push_back(T);\n }\n\n return trajectory;\n}\n\n\n\n\n\n\nint main(int argc, char **argv){\n\n TrajectoryType estimated_trajectory = ReadTrajectory(estimated_file_path);\n TrajectoryType groundtruth_trajectory = ReadTrajectory(groundtruth_file_path);\n\n if (estimated_trajectory.size() != groundtruth_trajectory.size()){\n std::cerr << \"the length of estimate_trajectory != length of groundtruth trajectory!\" << std::endl;\n }\n\n double total_error = 0, error;\n\n for(size_t i = 0; i < estimated_trajectory.size(); i++){\n Sophus::SE3d T_estimated = estimated_trajectory[i];\n Sophus::SE3d T_groundtruth = groundtruth_trajectory[i];\n\n error = (T_groundtruth.inverse() * T_estimated).log().norm();\n total_error += error * error;\n }\n\n double rmse = sqrt(total_error / estimated_trajectory.size());\n \n std::cout << \"RMSE = \" << rmse << std::endl;\n\n return 0;\n}\n\n\n\n", "meta": {"hexsha": "fe1fc48826273215d7a3f0e3f483cc325ed774c4", "size": 1685, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "my_implementation_2/ch4/example/trajectoryError.cpp", "max_stars_repo_name": "Mingrui-Yu/slambook2", "max_stars_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-09T14:18:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-09T14:18:15.000Z", "max_issues_repo_path": "my_implementation_2/ch4/example/trajectoryError.cpp", "max_issues_repo_name": "Mingrui-Yu/slambook2", "max_issues_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "my_implementation_2/ch4/example/trajectoryError.cpp", "max_forks_repo_name": "Mingrui-Yu/slambook2", "max_forks_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7794117647, "max_line_length": 107, "alphanum_fraction": 0.6403560831, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.752761214737606}} {"text": "/*\n * Copyright (C) 2019 by AutoSense Organization. All rights reserved.\n * Gary Chan \n */\n\n#ifndef COMMON_INCLUDE_COMMON_GEOMETRY_HPP_\n#define COMMON_INCLUDE_COMMON_GEOMETRY_HPP_\n\n#include \n#include \n\n#include \"common/types/object.hpp\" // ObjectPtr\n\nnamespace autosense {\nnamespace common {\nnamespace geometry {\n/**\n * @brief compute velocity's angle change between \"v1\" and \"v2\"\n * @note\n * v1·v2 = |v1|*|v2|cos(theta)\n * v1xv2 = |v1|*|v2|sin(theta)\n * @param v1\n * @param v2\n * @return\n */\ntemplate \nstatic double computeTheta2dXyBetweenVectors(const VectorT& v1,\n const VectorT& v2) {\n double v1_len = sqrt((v1.head(2).cwiseProduct(v1.head(2))).sum());\n double v2_len = sqrt((v2.head(2).cwiseProduct(v2.head(2))).sum());\n\n // cos(theta) = (v1·v2)/(|v1|*|v2|) = [v1(0)*v2(0)+v1(1)*v2(1)]/(|v1|*|v2|)\n double cos_theta =\n (v1.head(2).cwiseProduct(v2.head(2))).sum() / (v1_len * v2_len);\n // limit theta to [0, PI] or [-PI, 0]\n if (cos_theta > 1) {\n cos_theta = 1;\n }\n if (cos_theta < -1) {\n cos_theta = -1;\n }\n\n // sin(theta) = (v1xv2)/(|v1|*|v2|) = [v1(0)*v2(1)-v1(1)*v2(0)]/(|v1|*|v2|)\n double sin_theta = (v1(0) * v2(1) - v1(1) * v2(0)) / (v1_len * v2_len);\n // return [0, PI]\n double theta = acos(cos_theta);\n if (sin_theta < 0) {\n theta = -theta;\n }\n\n return theta;\n}\n\n/**\n * @breif compute velocity's angle cos value between \"v1\" and \"v2\"\n * @param v1\n * @param v2\n * @return\n */\nstatic double computeCosTheta2dXyBetweenVectors(const Eigen::Vector3f& v1,\n const Eigen::Vector3f& v2) {\n double v1_len = sqrt((v1.head(2).cwiseProduct(v1.head(2))).sum());\n double v2_len = sqrt((v2.head(2).cwiseProduct(v2.head(2))).sum());\n double cos_theta =\n (v1.head(2).cwiseProduct(v2.head(2))).sum() / (v1_len * v2_len);\n return cos_theta;\n}\n\n/**\n * @breif compute 3D point's Sphere/Cylinder distance and corresponding norm\n * @tparam PointT\n * @param point\n * @return\n */\ntemplate \nstatic float calcSphereDistNorm(PointT point) {\n return pow(point.x, 2.0) + pow(point.y, 2.0) + pow(point.z, 2.0);\n}\n\ntemplate \nstatic float calcSphereDist(PointT point) {\n return sqrt(calcSphereDistNorm(point));\n}\n\ntemplate \nstatic float calcCylinderDistNorm(PointT point) {\n return pow(point.x, 2.0) + pow(point.y, 2.0);\n}\n\ntemplate \nstatic float calcCylinderDist(PointT point) {\n return sqrt(calcCylinderDistNorm(point));\n}\n\n// 计算点云重心\ntemplate \nstatic Eigen::Vector3d getCloudBarycenter(\n typename pcl::PointCloud::ConstPtr cloud) {\n int num_points = cloud->points.size();\n Eigen::Vector3d barycenter(0, 0, 0);\n\n for (int i = 0; i < num_points; i++) {\n const PointT& pt = cloud->points[i];\n barycenter[0] += pt.x;\n barycenter[1] += pt.y;\n barycenter[2] += pt.z;\n }\n\n if (num_points > 0) {\n barycenter[0] /= num_points;\n barycenter[1] /= num_points;\n barycenter[2] /= num_points;\n }\n return barycenter;\n}\n\n/**\n * @brief calculate yaw given direction vector, suppose coordinate vector: (1.0,\n * 0.0, 0.0)\n * @tparam VectorT\n * @param dir\n * @return yaw in rad\n */\ntemplate \nstatic double calcYaw4DirectionVector(const VectorT& dir) {\n const Eigen::Vector3d coord_dir(1.0, 0.0, 0.0);\n return computeTheta2dXyBetweenVectors(coord_dir, dir);\n}\n\n} // namespace geometry\n} // namespace common\n} // namespace autosense\n\n#endif // COMMON_INCLUDE_COMMON_GEOMETRY_HPP_\n", "meta": {"hexsha": "7353834b47db66b43cb8abb6af23a0ae9da9f192", "size": 3744, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "LetsGo/ThirdParty/ObjectBuilder/Includes/common/geometry.hpp", "max_stars_repo_name": "wis1906/letsgo-ar-space-generation", "max_stars_repo_head_hexsha": "02d888a44bb9eb112f308356ab42720529349338", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LetsGo/ThirdParty/ObjectBuilder/Includes/common/geometry.hpp", "max_issues_repo_name": "wis1906/letsgo-ar-space-generation", "max_issues_repo_head_hexsha": "02d888a44bb9eb112f308356ab42720529349338", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LetsGo/ThirdParty/ObjectBuilder/Includes/common/geometry.hpp", "max_forks_repo_name": "wis1906/letsgo-ar-space-generation", "max_forks_repo_head_hexsha": "02d888a44bb9eb112f308356ab42720529349338", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7333333333, "max_line_length": 80, "alphanum_fraction": 0.6298076923, "num_tokens": 1200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7527372779794446}} {"text": "#pragma once\n\n#include \n#include \n\nusing namespace Eigen;\n\n/**\n * @brief Calcola la direzione normale di ogni triangolo nella mesh in input.\n *\n * Data una mesh di triangoli M = (V, F), dove V e' un array di posizioni 3D\n * (i vertici) e F e' un array di triple di indici ai vertici (ogni tripla\n * rappresenta una faccia triangolare), questa funzione calcola la direzione\n * normale di ogni triangolo.\n *\n * La direzione normale di un triangolo e' la direzione normale del piano su\n * cui giace. Questa viene calcolata come il prodotto vettoriale tra i vettori\n * che rappresentano due lati del triangolo centrati sul vertice a comune,\n * presi in senso antiorario, e normalizzato (cioe' reso unitario: lunghezza 1):\n *\n * C\n * *\n * / \\ (B - A) ^ (C - A) ^\n * / \\ n = --------------------- |\n * / \\ ||(B - A) ^ (C - A)||\n * A *------------* B\n *\n * @param V I vertici della mesh. Per ogni riga della matrice V, la posizione\n * del vertice e' costituita dalle coordinate x,y,z memorizzate nelle\n * 3 colonne della riga.\n * @param F I triangoli della mesh. Per ogni riga della matrice F, il triangolo\n * e' descritto dagli indici i,j,k memorizzati nelle 3 colonne della\n * riga. Gli indici i,j,k si riferiscono ai 3 vertici A, B, C del\n * triangolo, memorizzati in V.row(i), V.row(j) e V.row(k),\n * rispettivamente. NOTA: per ogni triangolo, i 3 vertici sono da\n * considerarsi indicati in senso antiorario.\n * @return MatrixXd La matrice restituita ha una riga per ogni faccia triangolare\n * (N.rows() == F.rows()) e 3 colonne. Ogni riga corrisponde\n * alla direzione normale del triangolo corrispondente, avente\n * le 3 coordinate x,y,z.\n */\nMatrixXd perFaceNormals(MatrixXd const &V, MatrixXi const &F)\n{\n MatrixXd N(F.rows(), 3);\n\n // per leggere/scrivere un elemento di una matrice X: X(i,j)\n // per leggere/scrivere una riga di una matrice X: X.row(i) (un vettore orizzontale)\n // il vettore da un punto p0 a un altro punto p1: Vector3d v = p1 - p0;\n // il prodotto vettoriale tra 2 vettori: Vector3d c = v1.cross(v2);\n // normalizzare un vettore, in-place: c.normalize();\n // normalizzare un vettore, in una nuova variabile: Vector3d cn = c.normalized();\n\n for (int f = 0; f < F.rows(); ++f)\n {\n Vector3d A = V.row(F(f, 0));\n Vector3d B = V.row(F(f, 1));\n Vector3d C = V.row(F(f, 2));\n Vector3d e0 = B - A;\n Vector3d e1 = C - A;\n N.row(f) = e0.cross(e1).normalized();\n }\n\n return N;\n}", "meta": {"hexsha": "b257cb5d618198bde85b3cb3d90a6eec2e52bd87", "size": 2740, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "perFacenormals.hpp", "max_stars_repo_name": "giorgiomarcias/WS_geo_3D", "max_stars_repo_head_hexsha": "ea34450ed0daa38504df5c0d723ab41ac347abd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-11T16:16:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-11T16:16:28.000Z", "max_issues_repo_path": "perFacenormals.hpp", "max_issues_repo_name": "giorgiomarcias/WS_geo_3D", "max_issues_repo_head_hexsha": "ea34450ed0daa38504df5c0d723ab41ac347abd3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "perFacenormals.hpp", "max_forks_repo_name": "giorgiomarcias/WS_geo_3D", "max_forks_repo_head_hexsha": "ea34450ed0daa38504df5c0d723ab41ac347abd3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.8125, "max_line_length": 88, "alphanum_fraction": 0.5981751825, "num_tokens": 823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625031628428, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7526843030016005}} {"text": "///////////////////////////////////////////////////////////////////\n// Copyright Christopher Kormanyos 2021. //\n// Distributed under the Boost Software License, //\n// Version 1.0. (See accompanying file LICENSE_1_0.txt //\n// or copy at http://www.boost.org/LICENSE_1_0.txt) //\n///////////////////////////////////////////////////////////////////\n\n#include \n\n#if defined(__GNUC__)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wconversion\"\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wsign-conversion\"\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n#endif\n\n#if defined(__clang__) && !defined(__APPLE__)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wdeprecated-copy\"\n#endif\n\n#include \n#include \n\n#include \n\nnamespace math { namespace wide_decimal {\n\nnamespace detail {\n\ntemplate\nFloatingPointType sin_series(const FloatingPointType& x)\n{\n FloatingPointType term = x;\n const FloatingPointType x2 = x * x;\n FloatingPointType sum = x;\n bool term_is_neg = true;\n const FloatingPointType tol = std::numeric_limits::epsilon() * x;\n\n for(std::uint32_t k = 3U; k < UINT32_C(0xFFFF); k += 2U)\n {\n term *= x2;\n term /= std::uint32_t(k * std::uint32_t(k - 1U));\n\n if(term < tol)\n {\n break;\n }\n\n term_is_neg ? sum -= term : sum += term;\n\n term_is_neg = (!term_is_neg);\n }\n\n return sum;\n}\n\ntemplate\nFloatingPointType cos_series(const FloatingPointType& x)\n{\n const FloatingPointType x2 = x * x;\n FloatingPointType term = x2 / 2U;\n FloatingPointType sum = term;\n bool term_is_neg = true;\n const FloatingPointType tol = std::numeric_limits::epsilon() * x;\n\n for(std::uint32_t k = 4U; k < UINT32_C(0xFFFF); k += 2U)\n {\n term *= x2;\n term /= std::uint32_t(k * std::uint32_t(k - 1U));\n\n if(term < tol)\n {\n break;\n }\n\n term_is_neg ? sum -= term : sum += term;\n\n term_is_neg = (!term_is_neg);\n }\n\n return 1U - sum;\n}\n\n}\n\ntemplate\nFloatingPointType sin(const FloatingPointType& x)\n{\n using floating_point_type = FloatingPointType;\n\n floating_point_type s;\n\n if(x < 0)\n {\n s = -sin(-x);\n }\n else if(x > 0)\n {\n // Perform argument reduction and subsequent scaling of the result.\n\n // Given x = k * (pi/2) + r, compute n = (k % 4).\n\n // | n | sin(x) | cos(x) | sin(x)/cos(x) |\n // |----------------------------------------|\n // | 0 | sin(r) | cos(r) | sin(r)/cos(r) |\n // | 1 | cos(r) | -sin(r) | -cos(r)/sin(r) |\n // | 2 | -sin(r) | -cos(r) | sin(r)/cos(r) |\n // | 3 | -cos(r) | sin(r) | -cos(r)/sin(r) |\n\n const std::uint32_t k = (std::uint32_t) (x / boost::math::constants::half_pi());\n const std::uint_fast32_t n = (std::uint_fast32_t) (k % 4U);\n\n floating_point_type r = x - (boost::math::constants::half_pi() * k);\n\n const bool is_neg = (n > 1U);\n const bool is_cos = ((n == 1U) || (n == 3U));\n\n std::uint_fast32_t n_angle_identity = 0U;\n\n static const floating_point_type one_tenth = floating_point_type(1U) / 10U;\n\n // Reduce the argument with factors of three until it is less than 1/10.\n while(r > one_tenth)\n {\n r /= 3U;\n\n ++n_angle_identity;\n }\n\n s = (is_cos ? detail::cos_series(r) : detail::sin_series(r));\n\n // Rescale the result with the triple angle identity for sine.\n for(std::uint_fast32_t t = 0U; t < n_angle_identity; ++t)\n {\n s = (s * 3U) - (((s * s) * s) * 4U);\n }\n\n s = fabs(s);\n\n if(is_neg)\n {\n s = -s;\n }\n }\n else\n {\n s = 0;\n }\n\n return s;\n}\n\ntemplate\nFloatingPointType cos(const FloatingPointType& x)\n{\n using floating_point_type = FloatingPointType;\n\n floating_point_type c;\n\n if(x < 0)\n {\n c = cos(-x);\n }\n else if(x > 0)\n {\n // Perform argument reduction and subsequent scaling of the result.\n\n // Given x = k * (pi/2) + r, compute n = (k % 4).\n\n // | n | sin(x) | cos(x) | sin(x)/cos(x) |\n // |----------------------------------------|\n // | 0 | sin(r) | cos(r) | sin(r)/cos(r) |\n // | 1 | cos(r) | -sin(r) | -cos(r)/sin(r) |\n // | 2 | -sin(r) | -cos(r) | sin(r)/cos(r) |\n // | 3 | -cos(r) | sin(r) | -cos(r)/sin(r) |\n\n const std::uint32_t k = (std::uint32_t) (x / boost::math::constants::half_pi());\n const std::uint_fast32_t n = (std::uint_fast32_t) (k % 4U);\n\n floating_point_type r = x - (boost::math::constants::half_pi() * k);\n\n const bool is_neg = ((n == 1U) || (n == 2U));\n const bool is_sin = ((n == 1U) || (n == 3U));\n\n std::uint_fast32_t n_angle_identity = 0U;\n\n static const floating_point_type one_tenth = floating_point_type(1U) / 10U;\n\n // Reduce the argument with factors of three until it is less than 1/10.\n while(r > one_tenth)\n {\n r /= 3U;\n\n ++n_angle_identity;\n }\n\n c = (is_sin ? detail::sin_series(r) : detail::cos_series(r));\n\n // Rescale the result with the triple angle identity for cosine.\n for(std::uint_fast32_t t = 0U; t < n_angle_identity; ++t)\n {\n c = (((c * c) * c) * 4U) - (c * 3U);\n }\n\n c = fabs(c);\n\n if(is_neg)\n {\n c = -c;\n }\n }\n else\n {\n c = floating_point_type(1U);\n }\n\n return c;\n}\n\n} }\n\nnamespace local\n{\n template\n bool test_tgamma()\n {\n // N[Gamma[5/2], 120]\n const T control_tgamma_2_and_half(\"1.32934038817913702047362561250585888709816209209179034616035584238968346344327413603121299255390849906217011771821192800\");\n\n // N[Gamma[5000/2], 120]\n const T control_tgamma_2_fifty (\"1.29314250436364309292832582080974738839793748706951226669917697084512949902204448379552716614841127978037140294127577317E490\");\n\n const T tgamma_2_and_half = boost::math::tgamma(T(T(5) / 2));\n const T tgamma_2_fifty = boost::math::tgamma(T(T(500) / 2));\n\n const T closeness_2_and_half = fabs(1 - fabs(tgamma_2_and_half / control_tgamma_2_and_half));\n const T closeness_2_fifty = fabs(1 - fabs(tgamma_2_fifty / control_tgamma_2_fifty));\n\n const bool result_is_ok_2_and_half = (closeness_2_and_half < std::numeric_limits::epsilon() * T(1.0E5L));\n const bool result_is_ok_2_fifty = (closeness_2_fifty < std::numeric_limits::epsilon() * T(1.0E5L));\n\n const bool result_is_ok = (result_is_ok_2_and_half && result_is_ok_2_fifty);\n\n return result_is_ok;\n }\n}\n\nbool math::wide_decimal::example009b_boost_math_standalone()\n{\n using wide_decimal_010_type = math::wide_decimal::decwide_t< 10U, std::uint32_t, void>;\n using wide_decimal_035_type = math::wide_decimal::decwide_t< 35U, std::uint32_t, void>;\n using wide_decimal_105_type = math::wide_decimal::decwide_t<105U, std::uint32_t, void>;\n\n const bool result_010_is_ok = local::test_tgamma();\n const bool result_035_is_ok = local::test_tgamma();\n const bool result_105_is_ok = local::test_tgamma();\n\n const bool result_is_ok = ( result_010_is_ok\n && result_035_is_ok\n && result_105_is_ok);\n\n return result_is_ok;\n}\n\n// Enable this if you would like to activate this main() as a standalone example.\n#if 0\n\n#include \n#include \n\nint main()\n{\n const bool result_is_ok = math::wide_decimal::example009b_boost_math_standalone();\n\n std::cout << \"result_is_ok: \" << std::boolalpha << result_is_ok << std::endl;\n}\n\n#endif\n\n#if defined(__clang__) && !defined(__APPLE__)\n#pragma GCC diagnostic pop\n#endif\n\n#if defined(__GNUC__)\n#pragma GCC diagnostic pop\n#pragma GCC diagnostic pop\n#pragma GCC diagnostic pop\n#endif\n", "meta": {"hexsha": "e62aeb9a1fba1c63b24053f6baaa84b41f491d40", "size": 8089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/example009b_boost_math_standalone.cpp", "max_stars_repo_name": "ckormanyos/wide-decimal", "max_stars_repo_head_hexsha": "de65a9a348b3a164b64d5fcd89bb28c4755d95bc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2021-01-05T07:37:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T15:15:10.000Z", "max_issues_repo_path": "examples/example009b_boost_math_standalone.cpp", "max_issues_repo_name": "ckormanyos/wide-decimal", "max_issues_repo_head_hexsha": "de65a9a348b3a164b64d5fcd89bb28c4755d95bc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 49.0, "max_issues_repo_issues_event_min_datetime": "2020-11-01T14:48:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T08:45:25.000Z", "max_forks_repo_path": "examples/example009b_boost_math_standalone.cpp", "max_forks_repo_name": "ckormanyos/wide-decimal", "max_forks_repo_head_hexsha": "de65a9a348b3a164b64d5fcd89bb28c4755d95bc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-05T07:27:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-05T07:27:52.000Z", "avg_line_length": 27.7020547945, "max_line_length": 168, "alphanum_fraction": 0.6134256398, "num_tokens": 2378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.8152324915965391, "lm_q1q2_score": 0.7524915143048692}} {"text": "// MovementPatternFunctions.cpp : Defines the entry point for the console application.\r\n//\r\n\r\n/*\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n*/\r\n#include \"UDG_Hokuyo.h\"\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\n\r\nconst float PI = 3.14159265;\r\n\r\n\r\n\r\nvoid scanningPattern_rotateToAngle(vector& x_pos, vector& y_pos, float xC, float yC, float rotationAngle){\r\n\r\n\trotationAngle = rotationAngle*(PI / 180);\r\n\r\n\tfor (int i = 0; i < static_cast(x_pos.size()); i++)\r\n\t{\r\n\t\tx_pos[i] = cos(rotationAngle) * (x_pos[i] - xC) - sin(rotationAngle) * (y_pos[i] - yC) + xC;\r\n\t\ty_pos[i] = sin(rotationAngle) * (x_pos[i] - xC) + cos(rotationAngle) * (y_pos[i] - yC) + yC;\r\n\t}\r\n\r\n}\r\n\r\nvoid scanningPattern_horiz(vector& x_vec, vector& y_vec, vector& z_vec, float xC, float yC, float radius, float height, float rotAngle, float startAngle, float endAngle, float deltaPoints){\r\n\r\n\t\r\n\tif (startAngle > endAngle){\r\n\t\tdeltaPoints = -deltaPoints;\r\n\t}\r\n\r\n\tendAngle += deltaPoints;\r\n\r\n\tfor (float i = startAngle; i < endAngle; i = i+ deltaPoints)\r\n\t{\r\n\t\tx_vec.push_back(xC + radius*cos(i*(PI / 180)));\r\n\t\ty_vec.push_back(yC + radius*sin(i*(PI / 180)));\r\n\t\tz_vec.push_back(height);\r\n\t}\r\n\r\n\tscanningPattern_rotateToAngle(x_vec, y_vec, xC, yC, rotAngle);\r\n\r\n}\r\n\r\n\r\n//float calculatePCA_rotAngle(float positions[][2], int size){\r\nfloat calculatePCA_rotAngle(vector& x_pos, vector& y_pos){\r\n\t\r\n\tint size = x_pos.size();\r\n\r\n\tMatrixXf posMat(x_pos.size(), 2);\r\n\r\n\tfor (int i = 0; i < size; i++)\r\n\t{\r\n\t\tposMat(i, 0) = x_pos[i];\r\n\t\tposMat(i, 1) = y_pos[i];\r\n\t}\r\n\r\n\t/*\r\n\tfor (int i = 0; i < size; i++)\r\n\t{\r\n\t\tfor (int j = 0; j < 2; j++)\r\n\t\t{\r\n\t\t\tposMat(i, j) = positions[i][j];\r\n\t\t}\r\n\t}\r\n\t*/\r\n\r\n\r\n\r\n\tfloat avg_x = 0.0;\r\n\tfloat sum_x = 0.0;\r\n\tfloat avg_y = 0.0;\r\n\tfloat sum_y = 0.0;\r\n\tfor (int i = 0; i < size; i++)\r\n\t{\r\n\t\tsum_x += posMat(i, 0);\r\n\t\tsum_y += posMat(i, 1);\r\n\t}\r\n\tavg_x = ((float)sum_x) / size;\r\n\tavg_y = ((float)sum_y) / size;\r\n\r\n\tfor (int i = 0; i < size; i++)\r\n\t{\r\n\t\tposMat(i, 0) -= avg_x;\r\n\t\tposMat(i, 1) -= avg_y;\r\n\t}\r\n\r\n\tint fact = size - 1;\r\n\r\n\tMatrixXf covMat(2, 2);\r\n\tcovMat = (posMat.transpose()*posMat.conjugate()) / fact;\r\n\t\r\n\t/*\r\n\tstd::cout << covMat(0, 0) << ' ';\r\n\tstd::cout << covMat(0, 1) << std::endl;\r\n\tstd::cout << covMat(1, 0) << ' ';\r\n\tstd::cout << covMat(1, 1) << std::endl;\r\n*/\r\n\r\n\tEigenSolver es(covMat);\r\n\t/*\r\n\tcout << \"Eigenvalue:\"\r\n\t\t<< endl << es.eigenvalues() << endl;\r\n\r\n\tcout << \"Eigenvectors:\"\r\n\t\t<< endl << es.eigenvectors() << endl;\r\n\r\n\t*/\r\n\tfloat eigenvalueCalc[2] = { es.eigenvalues()[0].real(), es.eigenvalues()[1].real() };\r\n\r\n\tfloat eigenvectorCalc[2][2] = { { es.eigenvectors()(0, 0).real(), es.eigenvectors()(0, 1).real() }, { es.eigenvectors()(1, 0).real(), es.eigenvectors()(1, 1).real() } };\r\n\r\n\tint index = -1;\r\n\r\n\tif (eigenvalueCalc[0] > eigenvalueCalc[1])\r\n\t{\r\n\t\tindex = 0;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tindex = 1;\r\n\t}\r\n\r\n\tfloat maxEigenVec[2] = { eigenvectorCalc[0][index], eigenvectorCalc[1][index] };\r\n\t/*\r\n\tstd::cout << maxEigenVec[0] << ' ';\r\n\tstd::cout << maxEigenVec[1] << std::endl;\r\n\t*/\r\n\tfloat bladeRotAngle = atan2(maxEigenVec[0], maxEigenVec[1])*(180 / PI);\r\n\r\n\tif (bladeRotAngle < 0)\r\n\t{\r\n\t\tbladeRotAngle = bladeRotAngle + 180;\r\n\t}\r\n\r\n\t\r\n\r\n\treturn bladeRotAngle;\r\n\t\r\n}\r\n\r\n\r\nvoid lidarData_thresholdByDistance(vector& angles, vector& distances, float minDist, float maxDist){\r\n\r\n\tstd::vector results;\r\n\r\n\tauto it = std::find_if(std::begin(distances), std::end(distances), [maxDist, minDist](int i){return i > maxDist || i < minDist; });\r\n\twhile (it != std::end(distances)) {\r\n\t\tresults.emplace_back(std::distance(std::begin(distances), it));\r\n\t\tit = std::find_if(std::next(it), std::end(distances), [maxDist, minDist](int i){return i > maxDist || i < minDist; });\r\n\r\n\t}\r\n\r\n\r\n\r\n\r\n\r\n\tfor (size_t i = 0; i < results.size(); i++)\r\n\t{\r\n\r\n\t\tdistances[results[i]] = -1;\r\n\t\tangles[results[i]] = -1;\r\n\t}\r\n\r\n\tdistances.erase(remove(distances.begin(), distances.end(), -1), distances.end());\r\n\tangles.erase(remove(angles.begin(), angles.end(), -1), angles.end());\r\n\r\n\r\n\r\n}\r\n\r\n\r\ntuple calculateMeans(vector& angles, vector& distances){\r\n\r\n\tdouble meanDist = -1;\r\n\tdouble meanAngle = -1;\r\n\r\n\tmeanDist = accumulate(distances.begin(), distances.end(), 0.0) / distances.size();\r\n\r\n\r\n\tvector sinAngles;\r\n\tvector cosAngles;\r\n\r\n\r\n\r\n\tfor (size_t i = 0; i < angles.size(); i++)\r\n\t{\r\n\t\tsinAngles.push_back(sin(angles[i] * (PI / 180)));\r\n\t\tcosAngles.push_back(cos(angles[i] * (PI / 180)));\r\n\r\n\t}\r\n\r\n\tdouble avgSin = accumulate(sinAngles.begin(), sinAngles.end(), 0.0) / sinAngles.size();\r\n\r\n\tdouble avgCos = accumulate(cosAngles.begin(), cosAngles.end(), 0.0) / cosAngles.size();\r\n\r\n\r\n\r\n\r\n\tif (avgSin>0 && avgCos>0)\r\n\t{\r\n\t\tmeanAngle = atan(avgSin / avgCos);\r\n\t}\r\n\telse if (avgCos <0)\r\n\t{\r\n\t\tmeanAngle = atan(avgSin / avgCos) + 180 * (PI / 180);\r\n\t}\r\n\telse if (avgSin <0 && avgCos >0)\r\n\t{\r\n\t\tmeanAngle = atan(avgSin / avgCos) + 360 * (PI / 180);\r\n\t}\r\n\r\n\r\n\tmeanAngle = meanAngle * (180 / PI);\r\n\r\n\treturn make_tuple(meanAngle, meanDist);\r\n\r\n}\r\n\r\n\r\nvoid lidar_PolarToCart(double centerX, double centerY, vector& angles, vector& distances, vector& posX, vector& posY){\r\n\r\n\tfor (size_t i = 0; i < distances.size(); i++)\r\n\t{\r\n\t\tposX.push_back(centerX + distances[i] * sin(angles[i] * (PI / 180)));\r\n\t\tposY.push_back(centerY + distances[i] * cos(angles[i] * (PI / 180)));\r\n\t}\r\n\r\n}\r\n\r\n\r\ntuple getPathCenterFromMaxDist(vector& x_pos, vector& y_pos){\r\n\r\n\tdouble maxDistance = 0;\r\n\tdouble maxDistance_ind[2] = {-1,-1};\r\n\r\n\tdouble tempDist = 0;\r\n\tfor (size_t i = 0; i < x_pos.size(); i++)\r\n\t{\r\n\t\tfor (size_t j = 0; j < x_pos.size(); j++)\r\n\t\t{\r\n\t\t\ttempDist = sqrt(pow(x_pos[i] - x_pos[j], 2) + pow(y_pos[i] - y_pos[j], 2));\r\n\t\t\tif (tempDist > maxDistance)\r\n\t\t\t{\r\n\t\t\t\tmaxDistance = tempDist;\r\n\t\t\t\tmaxDistance_ind[0] = i;\r\n\t\t\t\tmaxDistance_ind[1] = j;\r\n\t\t\t}\r\n\r\n\t\t}\r\n\t}\r\n\r\n\tint path_centerIndex = max(maxDistance_ind[0], maxDistance_ind[1]);\r\n\tdouble path_centerX = x_pos[path_centerIndex];\r\n\tdouble path_centerY = y_pos[path_centerIndex];\r\n\r\n\treturn make_tuple(maxDistance, path_centerX, path_centerY, maxDistance_ind[0], maxDistance_ind[1]);\r\n\r\n}\r\n\r\n\r\n\r\n", "meta": {"hexsha": "10527e2078edb07d542207b5ff980ebfd15ce36d", "size": 6373, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MovementPatternFunctions.cpp", "max_stars_repo_name": "IvanNik17/LER_Drone", "max_stars_repo_head_hexsha": "4c75138f68af20913b685dec4e91e5c6c4644ff4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MovementPatternFunctions.cpp", "max_issues_repo_name": "IvanNik17/LER_Drone", "max_issues_repo_head_hexsha": "4c75138f68af20913b685dec4e91e5c6c4644ff4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MovementPatternFunctions.cpp", "max_forks_repo_name": "IvanNik17/LER_Drone", "max_forks_repo_head_hexsha": "4c75138f68af20913b685dec4e91e5c6c4644ff4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1745454545, "max_line_length": 211, "alphanum_fraction": 0.608190805, "num_tokens": 1970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632302488963, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7524767474360797}} {"text": "#include \n#include \"numerical_gradient.h\"\n\nnamespace MyDL{\n\n using namespace Eigen;\n\n MatrixXd numerical_gradient(double (*f)(MatrixXd), MatrixXd x){\n double h = 1e-4;\n int size_x = x.rows() * x.cols();\n MatrixXd grad(x.rows(), x.cols());\n\n for(int i = 0; i < size_x; i++){\n double tmp_val = x(i);\n double f_plus_h;\n double f_minus_h;\n\n // f(x + h)\n x(i) = tmp_val + h;\n f_plus_h = f(x);\n\n // f(x - h)\n x(i) = tmp_val - h;\n f_minus_h = f(x);\n \n grad(i) = (f_plus_h - f_minus_h) / (2*h);\n\n x(i) = tmp_val;\n }\n\n return grad;\n }\n\n // TwoLayerNetなどで用いるもの(ラムダ式使用・DNNのインスタンスに含まれるパラメータを参照して使用する場合)\n MatrixXd numerical_gradient(const std::function& f, MatrixXd& x)\n {\n double h = 1e-4;\n int size_x = x.rows() * x.cols();\n MatrixXd grad(x.rows(), x.cols());\n\n for (int i = 0; i < size_x; i++)\n {\n double tmp_val = x(i);\n double f_plus_h;\n double f_minus_h;\n\n // f(x + h)\n x(i) = tmp_val + h;\n f_plus_h = f(x);\n\n // f(x - h)\n x(i) = tmp_val - h;\n f_minus_h = f(x);\n\n grad(i) = (f_plus_h - f_minus_h) / (2 * h);\n\n x(i) = tmp_val;\n }\n\n return grad;\n }\n}", "meta": {"hexsha": "ee6406c9db046df2cc5f7f2dcf09db477a7b6a68", "size": 1437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simple_lib/src/numerical_gradient.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": "simple_lib/src/numerical_gradient.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": "simple_lib/src/numerical_gradient.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": 23.1774193548, "max_line_length": 86, "alphanum_fraction": 0.4516353514, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7524557434936789}} {"text": "#include \n#include \n#include \n\nusing Eigen::VectorXf;\nusing Eigen::MatrixXf;\nusing namespace LBFGSpp;\n\nclass Rosenbrock\n{\nprivate:\n int n;\n uint64_t ncalls = 0;\n float delta = 1e-7;\npublic:\n Rosenbrock(int n_) : n(n_) {}\n float operator()(const VectorXf& x, VectorXf& grad)\n {\n ncalls++;\n if (ncalls != 1) return getForward(x);\n\n float fx = 0.0;\n for(int i = 0; i < n; i += 2)\n {\n float t1 = 1.0 - x[i];\n float t2 = 10 * (x[i + 1] - x[i] * x[i]);\n grad[i + 1] = 20 * t2;\n grad[i] = -2.0 * (x[i] * grad[i + 1] + t1);\n fx += t1 * t1 + t2 * t2;\n }\n return fx;\n }\n float getForward(const VectorXf& x)\n {\n float fx = 0.0;\n for(int i = 0; i < n; i += 2)\n {\n float t1 = 1.0 - x[i];\n float t2 = 10 * (x[i + 1] - x[i] * x[i]);\n fx += t1 * t1 + t2 * t2;\n }\n return fx;\n }\n float getDg(const VectorXf& drt, const VectorXf& x1, const float& fx)\n {\n float res = 0;\n VectorXf x2 = x1 + delta * drt;\n float fx2 = getForward(x2);\n res = ( fx2 - fx ) / delta;\n return res;\n }\n void getGrad(const VectorXf& x, VectorXf& grad)\n {\n for(int i = 0; i < n; i += 2)\n {\n float t1 = 1.0 - x[i];\n float t2 = 10 * (x[i + 1] - x[i] * x[i]);\n grad[i + 1] = 20 * t2;\n grad[i] = -2.0 * (x[i] * grad[i + 1] + t1);\n }\n }\n};\n\nint main()\n{\n const int n = 10;\n LBFGSParam param;\n LBFGSSolver solver(param);\n Rosenbrock fun(n);\n\n VectorXf x = VectorXf::Zero(n);\n float fx;\n int niter = solver.minimize(fun, x, fx);\n\n std::cout << niter << \" iterations\" << std::endl;\n std::cout << \"x = \\n\" << x.transpose() << std::endl;\n std::cout << \"f(x) = \" << fx << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "a2e5e06148bdd0e9de6665f1565fdb1249ee9f87", "size": 1947, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example-rosenbrock_new.cpp", "max_stars_repo_name": "alexrocrod/BFGSxSIMD", "max_stars_repo_head_hexsha": "b089f9c92ef2b068d91a3ae6ff5ca57698812ab3", "max_stars_repo_licenses": ["MIT"], "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-rosenbrock_new.cpp", "max_issues_repo_name": "alexrocrod/BFGSxSIMD", "max_issues_repo_head_hexsha": "b089f9c92ef2b068d91a3ae6ff5ca57698812ab3", "max_issues_repo_licenses": ["MIT"], "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-rosenbrock_new.cpp", "max_forks_repo_name": "alexrocrod/BFGSxSIMD", "max_forks_repo_head_hexsha": "b089f9c92ef2b068d91a3ae6ff5ca57698812ab3", "max_forks_repo_licenses": ["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.037037037, "max_line_length": 73, "alphanum_fraction": 0.4524910118, "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7523778109727787}} {"text": "\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\nclass matrix\n{\n\tint rows,cols;\n\tfloat a[10][10];\npublic:\n\tvoid dimensions(int r,int c)\n\t{\n\t\trows=r;\n\t\tcols=c;\n\t\tfor(int i=0;i(\"matrix\")\n\t\t.def(\"dimensions\",&matrix::dimensions)\n\t\t.def(\"read\",&matrix::read)\n\t\t.def(\"display\",&matrix::display)\n\t\t.def(\"cofactor\",&matrix::cofactor)\n\t\t.def(\"determinant\",&matrix::determinant)\n\t\t.def(\"adjoint\",&matrix::adjoint)\n\t\t.def(\"inverse\",&matrix::inverse)\n\t\t.def(self+self)\n\t\t.def(self-self)\n\t\t.def(self*self)\n//\t\t.def(++self)\n\t\t.def(self&self)\n\t;\n}\n", "meta": {"hexsha": "29c319d6527207880145602d7f569a910aa4d88c", "size": 3497, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matrix.cpp", "max_stars_repo_name": "RKJenamani/Matrix-Calculator", "max_stars_repo_head_hexsha": "2554db2a249974aa9ec295482a1af93c39eb845b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "matrix.cpp", "max_issues_repo_name": "RKJenamani/Matrix-Calculator", "max_issues_repo_head_hexsha": "2554db2a249974aa9ec295482a1af93c39eb845b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-02-06T22:25:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-06T22:25:56.000Z", "max_forks_repo_path": "matrix.cpp", "max_forks_repo_name": "RKJenamani/Matrix-Calculator", "max_forks_repo_head_hexsha": "2554db2a249974aa9ec295482a1af93c39eb845b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9401197605, "max_line_length": 74, "alphanum_fraction": 0.5115813554, "num_tokens": 1156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794594, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7521063216170402}} {"text": "#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n cout.precision(3);\n Matrix3f A(3,3);\nA << 1,2,3, 4,5,6, 7,8,10;\nMatrix B;\nB << 3,1, 3,1, 4,1;\nMatrix X;\nX = A.fullPivLu().solve(B);\ncout << \"The solution with right-hand side (3,3,4) is:\" << endl;\ncout << X.col(0) << endl;\ncout << \"The solution with right-hand side (1,1,1) is:\" << endl;\ncout << X.col(1) << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "115e105d2add038fccfbeafc2fae4c5573de0eb5", "size": 469, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tutorial_solve_multiple_rhs.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_Tutorial_solve_multiple_rhs.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_Tutorial_solve_multiple_rhs.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": 20.3913043478, "max_line_length": 64, "alphanum_fraction": 0.6076759062, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7520019119082986}} {"text": "#include \n#include \n#include \n#include \n\nstatic unsigned long long gcd(unsigned long long a, unsigned long long b) {\n unsigned long long c;\n while (a != 0) {\n c = a;\n a = b % a;\n b = c;\n }\n return b;\n}\n\nstatic bool is_prime(unsigned int number) {\n const unsigned int upper_limit = std::floor(std::sqrt(number));\n\n for (unsigned int a = 2; a <= upper_limit; a++) {\n if (number % a == 0) {\n return false;\n }\n }\n return true;\n}\n\nvoid output_coprimes(const unsigned int composite_number, const unsigned int length) {\n unsigned output_length = 0;\n unsigned current_number = 2;\n\n while (output_length < length) {\n if (gcd(current_number, composite_number) == 1) {\n std::cout << current_number << \"\\n\";\n output_length++;\n }\n current_number++;\n }\n}\n\nvoid output_primes(const unsigned int composite_number, const unsigned int length) {\n unsigned output_length = 0;\n unsigned current_number = 2;\n\n while (output_length < length) {\n if (is_prime(current_number) && gcd(current_number, composite_number) == 1) {\n std::cout << current_number << \"\\n\";\n output_length++;\n }\n current_number++;\n }\n}\n\nint main(int argc, char** argv) {\n namespace po = boost::program_options;\n po::options_description description(\"JKQ DDSIM by https://iic.jku.at/eda/ -- Allowed options\");\n description.add_options()(\"help,h\", \"produce help message\")(\"composite_number,N\", po::value()->required(),\n \"number of measurements on the final quantum state\")(\"strategy,S\", po::value()->required(),\n \"strategy for prime base generation (primes, coprimes)\")(\"length,L\", po::value()->required(), \"how many bases to generate\");\n po::variables_map vm;\n try {\n po::store(po::parse_command_line(argc, argv, description), vm);\n if (vm.count(\"help\")) {\n std::cout << description;\n return 0;\n }\n po::notify(vm);\n } catch (const po::error& e) {\n std::cerr << \"[ERROR] \" << e.what() << \"! Try option '--help' for available commandline options.\\n\";\n std::exit(1);\n }\n\n if (vm[\"strategy\"].as() == \"coprimes\") {\n output_coprimes(vm[\"composite_number\"].as(), vm[\"length\"].as());\n } else if (vm[\"strategy\"].as() == \"primes\") {\n output_primes(vm[\"composite_number\"].as(), vm[\"length\"].as());\n } else {\n std::cerr << \"Invalid stragety.\\n\";\n }\n}", "meta": {"hexsha": "ee09dbc4064060c8f0ae1ae0c39875f5314e5467", "size": 2837, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/primebases.cpp", "max_stars_repo_name": "iic-jku/ddsim", "max_stars_repo_head_hexsha": "36661b7ec71a6c6f0cbf7abfb67fbba3f192926c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2020-02-25T16:19:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T14:31:39.000Z", "max_issues_repo_path": "apps/primebases.cpp", "max_issues_repo_name": "iic-jku/ddsim", "max_issues_repo_head_hexsha": "36661b7ec71a6c6f0cbf7abfb67fbba3f192926c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2020-03-03T23:07:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T16:58:49.000Z", "max_forks_repo_path": "apps/primebases.cpp", "max_forks_repo_name": "iic-jku/ddsim", "max_forks_repo_head_hexsha": "36661b7ec71a6c6f0cbf7abfb67fbba3f192926c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2020-04-14T00:44:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-18T21:28:05.000Z", "avg_line_length": 35.9113924051, "max_line_length": 255, "alphanum_fraction": 0.562918576, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225518, "lm_q2_score": 0.8080672227971212, "lm_q1q2_score": 0.7518728200040903}} {"text": "\n#include \n#include \"problem.h\"\n#include \"random.h\"\n#include \"so3.h\"\n\n#include \n\nvoid compute_error( const Eigen::Matrix3d &R, const Eigen::Vector3d &t,\n const Eigen::Matrix3d &Rsoln, const Eigen::Vector3d &tsoln,\n double &rot_angle_err, double &trans_angle_err, double &trans_scale_err )\n{\n Eigen::Matrix3d Rdiff = R*Rsoln.transpose();\n Eigen::Vector3d rdiff = so3ln(Rdiff);\n rot_angle_err = rdiff.norm();\n\n trans_angle_err = acos(t.dot(tsoln)/t.norm()/tsoln.norm());\n\n if ( isnan(trans_angle_err) ) trans_angle_err = 0;\n trans_scale_err = tsoln.norm()/t.norm();\n}\n\nvoid generateProblem( double trans_mag, double angle, double noise, Problem &prob, int nrays )\n{\n Eigen::Vector3d X; // 3D points\n Eigen::Vector3d cu; // camera centers for first multi-camera rig\n Eigen::Vector3d cv; // camera centers for second multi-camera rig\n Eigen::Vector3d PX; // 3D points after R,t transformation\n Ray u; // observations in first multi-camera rig\n Ray v; // observations in second multi-camera rig\n\n Eigen::Vector3d w = rand3f();\n w = w/w.norm();\n double theta = angle*M_PI/180;\n prob.R = so3exp(w*theta); // random rotation\n prob.t = rand3f(); // random translation\n while ( prob.t.norm() < 1e-10 ) prob.t = rand3f();\n prob.t = prob.t/prob.t.norm()*trans_mag;\n\n prob.ray_pairs.clear();\n\n for ( size_t i = 0; i < nrays; i++ ) {\n X = rand3f(); // sample random point\n while ( X.norm() == 0 ) X = rand3f();\n X = X/X.norm();\n double scale_factor = ((double)rand()/RAND_MAX) * 4 + 4;\n X *= scale_factor;\n\n cu = rand3f(); // sample random camera locations\n cv = rand3f(); // inter-camera\n //cv = cu; // intra-camera\n\n PX = prob.R*X+prob.t; // transform point\n u.x = X-cu; // make observation rays\n u.c = cu;\n v.x = PX-cv;\n v.c = cv;\n\n if ( noise > 0. ) // add noise with requested standard deviation\n {\n double unorm = u.x.norm();\n Eigen::Vector3d uproj = u.x/u.x(2);\n uproj.head(2) += grand2f()*noise;\n uproj /= uproj.norm();\n uproj *= unorm;\n if ( (X-cu).dot(uproj) < 0 ) uproj = -uproj;\n u.x = uproj;\n\n double vnorm = v.x.norm();\n Eigen::Vector3d vproj = v.x/v.x(2);\n vproj.head(2) += grand2f()*noise;\n vproj /= vproj.norm();\n vproj *= vnorm;\n if ( (PX-cv).dot(vproj) < 0 ) vproj = -vproj;\n v.x = vproj;\n }\n\n prob.ray_pairs.push_back( RayPair( u, v ) );\n }\n}\n\n", "meta": {"hexsha": "b65f1c8d84e9dceb3c7964a41c272911cf050f96", "size": 2742, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/problem.cpp", "max_stars_repo_name": "MikhailTerekhov/multi-camera-motion", "max_stars_repo_head_hexsha": "acefa9e9b659b46dfee48b5091a8acb0ff5a0ecf", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/problem.cpp", "max_issues_repo_name": "MikhailTerekhov/multi-camera-motion", "max_issues_repo_head_hexsha": "acefa9e9b659b46dfee48b5091a8acb0ff5a0ecf", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/problem.cpp", "max_forks_repo_name": "MikhailTerekhov/multi-camera-motion", "max_forks_repo_head_hexsha": "acefa9e9b659b46dfee48b5091a8acb0ff5a0ecf", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4390243902, "max_line_length": 94, "alphanum_fraction": 0.5423048869, "num_tokens": 777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7515926908997203}} {"text": "#include \"sophus/se3.hpp\"\n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace Eigen;\n\n/// Basic Sophus implementation\n\nint main(int argc, char **argv) {\n\n // Rotation of 90 degrees about thez axis\n Matrix3d R = AngleAxisd(M_PI / 2, Vector3d(0, 0, 1)).toRotationMatrix();\n // Quaternion object\n Quaterniond q(R);\n Sophus::SO3d SO3_R(R); // Sophus::SO3d Lie algebra object from rotation matrix\n Sophus::SO3d SO3_q(q); // Same lie algebra object from quaternion\n // Print the SO3 matrix from both the lie algebra object\n cout << \"SO(3) from matrix:\\n\" << SO3_R.matrix() << endl;\n cout << \"SO(3) from quaternion:\\n\" << SO3_q.matrix() << endl;\n cout << \"they are equal\" << endl;\n\n // Log is the 3D vector Lie Algebra representation of the rotation matrix\n Vector3d so3 = SO3_R.log();\n cout << \"so3 = \" << so3.transpose() << endl;\n // hat representation which is the skew symmetric matrix\n cout << \"so3 hat=\\n\" << Sophus::SO3d::hat(so3) << endl;\n // vee gets the vector from the skew symmetric matrix\n cout << \"so3 hat vee= \" << Sophus::SO3d::vee(Sophus::SO3d::hat(so3)).transpose() << endl;\n\n // Apply a left perturbation\n Vector3d update_so3(1e-4, 0, 0); // A small perturbation\n // Get the lie group (Rotation matrix) from the rotation vector and apply the rotation\n Sophus::SO3d SO3_updated = Sophus::SO3d::exp(update_so3) * SO3_R;\n cout << \"SO3 updated = \\n\" << SO3_updated.matrix() << endl;\n\n cout << \"*******************************\" << endl;\n // SE3 sophus\n Vector3d t(1, 0, 0); // Translation by 1m\n Sophus::SE3d SE3_Rt(R, t); // Lie Algebra from R,t SE(3)\n Sophus::SE3d SE3_qt(q, t); // Lie Algebra from q,t SE(3)\n cout << \"SE3 from R,t= \\n\" << SE3_Rt.matrix() << endl;\n cout << \"SE3 from q,t= \\n\" << SE3_qt.matrix() << endl;\n // Lie Algebra for SE3 is a 6 Dof Vector\n typedef Eigen::Matrix Vector6d;\n Vector6d se3 = SE3_Rt.log();\n cout << \"se3 = \" << se3.transpose() << endl;\n // Get the hat and recover the vector format of Lie Algebra from the hat\n cout << \"se3 hat = \\n\" << Sophus::SE3d::hat(se3) << endl;\n cout << \"se3 hat vee = \" << Sophus::SE3d::vee(Sophus::SE3d::hat(se3)).transpose() << endl;\n\n // Left perturb SE3\n Vector6d update_se3; // Small perturbation in roh\n update_se3.setZero();\n update_se3(0, 0) = 1e-4;\n Sophus::SE3d SE3_updated = Sophus::SE3d::exp(update_se3) * SE3_Rt;\n cout << \"SE3 updated = \" << endl << SE3_updated.matrix() << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "44393524ef799801eca7cd8bfa18082c55654061", "size": 2518, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch4/useSophus.cpp", "max_stars_repo_name": "RachitB11/slambook2", "max_stars_repo_head_hexsha": "71364203ecd0bd0f2dd6e9d9bd4bd80f049bbfc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch4/useSophus.cpp", "max_issues_repo_name": "RachitB11/slambook2", "max_issues_repo_head_hexsha": "71364203ecd0bd0f2dd6e9d9bd4bd80f049bbfc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch4/useSophus.cpp", "max_forks_repo_name": "RachitB11/slambook2", "max_forks_repo_head_hexsha": "71364203ecd0bd0f2dd6e9d9bd4bd80f049bbfc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9682539683, "max_line_length": 92, "alphanum_fraction": 0.6433677522, "num_tokens": 839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7515806227112538}} {"text": "#include \n#include \n#include \n#include \"aggregate_gen_SA.hpp\"\nusing namespace Eigen;\nusing namespace std;\n\n//return pos_sph matrix\nMatrixXd aggregate_gen_SA(const double& a, const int& num_sph, const double& kf, const double& Df, const double& tol){\n MatrixXd pos_sph= MatrixXd::Zero(3,num_sph);\n pos_sph.col(0) << -a,0,0;\n pos_sph.col(1) << a,0,0;\n\n Vector3d pos_cand(3);\n double rN;\n double phi;\n double u;\n ArrayXd dist_sph;\n\n for(int N=3; N <= num_sph; ++N){\n rN= N*N*a*a/(N-1)*pow(N/kf,2/Df)-N*a*a/(N-1)-N*a*a*pow((N-1)/kf,2/Df);\n rN= sqrt(rN);\n dist_sph.resize(N-1);\n\n while(1){\n phi= 2*M_PI*urf(re);\n u= 2*urf(re)-1;\n pos_cand << sqrt(1.0-u*u)*cos(phi), sqrt(1.0-u*u)*sin(phi), u;\n pos_cand *= rN;\n\n for(int i= 0; i < N-1; ++i){\n dist_sph(i)=(pos_sph.col(i)-pos_cand).norm();\n }\n\n if(dist_sph.minCoeff() < 2*a+tol && dist_sph.minCoeff() > 2*a){\n pos_sph.col(N-1)= pos_cand;\n pos_sph.colwise() -= pos_sph.rowwise().mean(); // translate the centroid to origin\n break;\n }\n }\n }\n\n // final check of the attached condition\n ArrayXd mindist_c(num_sph);\n for(int i= 0; i< num_sph; ++i){\n mindist_c(i)=((pos_sph.colwise()-pos_sph.col(i)).colwise().norm().array()-2*a).array().abs().minCoeff();\n }\n assert(mindist_c.maxCoeff() < tol);\n\n return pos_sph;\n}\n", "meta": {"hexsha": "86c68634e76a30aa2bcd0254f4e07efdaadcafa2", "size": 1519, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aggregate_gen_SA.cpp", "max_stars_repo_name": "nmoteki/aggregate_generator", "max_stars_repo_head_hexsha": "93ce7699405ba42e4d4dbdd78d48cdd1db8f3344", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-10-27T08:12:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-09T14:22:46.000Z", "max_issues_repo_path": "aggregate_gen_SA.cpp", "max_issues_repo_name": "nmoteki/aggregate_generator", "max_issues_repo_head_hexsha": "93ce7699405ba42e4d4dbdd78d48cdd1db8f3344", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aggregate_gen_SA.cpp", "max_forks_repo_name": "nmoteki/aggregate_generator", "max_forks_repo_head_hexsha": "93ce7699405ba42e4d4dbdd78d48cdd1db8f3344", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-10-23T09:40:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T20:13:32.000Z", "avg_line_length": 29.2115384615, "max_line_length": 118, "alphanum_fraction": 0.5483870968, "num_tokens": 489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145179, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7512144120674441}} {"text": "// https://www.boost.org/doc/libs/1_67_0/libs/math/example/numerical_derivative_example.cpp\n\n// Copyright Christopher Kormanyos 2013.\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#ifdef _MSC_VER\n# pragma warning (disable : 4996) // assignment operator could not be generated.\n#endif\n\n# include \n# include \n# include \n# include \n\n#include \n#include \n#include // for float_distance\n\n//[numeric_derivative_example\n/*`The following example shows how multiprecision calculations can be used to\nobtain full precision in a numerical derivative calculation that suffers from precision loss.\n\nConsider some well-known central difference rules for numerically\ncomputing the 1st derivative of a function [f'(x)] with [/x] real.\n\nNeed a reference here? Introduction to Partial Differential Equations, Peter J. Olver\n December 16, 2012 \n\nHere, the implementation uses a C++ template that can be instantiated with various\nfloating-point types such as `float`, `double`, `long double`, or even\na user-defined floating-point type like __multiprecision.\n\nWe will now use the derivative template with the built-in type `double` in\norder to numerically compute the derivative of a function, and then repeat\nwith a 5 decimal digit higher precision user-defined floating-point type. \n\nConsider the function shown below.\n!!\n(3)\nWe will now take the derivative of this function with respect to x evaluated\nat x = 3= 2. In other words,\n\n(4)\n\nThe expected result is\n\n 0:74535 59924 99929 89880 . (5)\nThe program below uses the derivative template in order to perform\nthe numerical calculation of this derivative. The program also compares the\nnumerically-obtained result with the expected result and reports the absolute\nrelative error scaled to a deviation that can easily be related to the number of\nbits of lost precision.\n\n*/\n\n/*` [note Rquires the C++11 feature of\n[@http://en.wikipedia.org/wiki/Anonymous_function#C.2B.2B anonymous functions]\nfor the derivative function calls like `[]( const double & x_) -> double`.\n*/\n\n\n\ntemplate \nvalue_type derivative (const value_type x, const value_type dx, function_type function)\n{\n /*! \\brief Compute the derivative of function using a 3-point central difference rule of O(dx^6).\n \\tparam value_type, floating-point type, for example: `double` or `cpp_dec_float_50`\n \\tparam function_type \n \n \\param x Value at which to evaluate derivative.\n \\param dx Incremental step-size.\n \\param function Function whose derivative is to computed.\n \n \\return derivative at x.\n */\n\n BOOST_STATIC_ASSERT_MSG(false == std::numeric_limits::is_integer, \"value_type must be a floating-point type!\");\n\n const value_type dx2(dx * 2U);\n const value_type dx3(dx * 3U);\n // Difference terms.\n const value_type m1 ((function (x + dx) - function(x - dx)) / 2U);\n const value_type m2 ((function (x + dx2) - function(x - dx2)) / 4U);\n const value_type m3 ((function (x + dx3) - function(x - dx3)) / 6U);\n const value_type fifteen_m1 (m1 * 15U);\n const value_type six_m2 (m2 * 6U);\n const value_type ten_dx (dx * 10U);\n return ((fifteen_m1 - six_m2) + m3) / ten_dx; // Derivative.\n} // \n\n#include \n using boost::multiprecision::number;\n using boost::multiprecision::cpp_dec_float;\n\n// Re-compute using 5 extra decimal digits precision (22) than double (17).\n#define MP_DIGITS10 unsigned (std::numeric_limits::max_digits10 + 5)\n\ntypedef cpp_dec_float mp_backend;\ntypedef number mp_type;\n\n\nint main()\n{\n {\n const double d =\n derivative\n ( 1.5, // x = 3.2\n std::ldexp (1., -9), // step size 2^-9 = see below for choice.\n [](const double & x)->double // Function f(x).\n {\n return std::sqrt((x * x) - 1.) - std::acos(1. / x);\n }\n );\n \n // The 'exactly right' result is [sqrt]5 / 3 = 0.74535599249992989880.\n const double rel_error = (d - 0.74535599249992989880) / 0.74535599249992989880;\n const double bit_error = std::abs(rel_error) / std::numeric_limits::epsilon();\n std::cout.precision (std::numeric_limits::digits10); // Show all guaranteed decimal digits.\n std::cout << std::showpoint ; // Ensure that any trailing zeros are shown too.\n\n std::cout << \" derivative : \" << d << std::endl;\n std::cout << \" expected : \" << 0.74535599249992989880 << std::endl;\n // Can compute an 'exact' value using multiprecision type.\n std::cout << \" expected : \" << sqrt(static_cast(5))/3U << std::endl;\n std::cout << \" bit_error : \" << static_cast(bit_error) << std::endl;\n\n std::cout.precision(6);\n std::cout << \"float_distance = \" << boost::math::float_distance(0.74535599249992989880, d) << std::endl;\n\n }\n\n { // Compute using multiprecision type with an extra 5 decimal digits of precision.\n const mp_type mp =\n derivative(mp_type(mp_type(3) / 2U), // x = 3/2\n mp_type(mp_type(1) / 10000000U), // Step size 10^7.\n [](const mp_type & x)->mp_type\n {\n return sqrt((x * x) - 1.) - acos (1. / x); // Function\n }\n );\n\n const double d = mp.convert_to(); // Convert to closest double.\n const double rel_error = (d - 0.74535599249992989880) / 0.74535599249992989880;\n const double bit_error = std::abs (rel_error) / std::numeric_limits::epsilon();\n std::cout.precision (std::numeric_limits ::digits10); // All guaranteed decimal digits.\n std::cout << std::showpoint ; // Ensure that any trailing zeros are shown too.\n std::cout << \" derivative : \" << d << std::endl;\n // Can compute an 'exact' value using multiprecision type.\n std::cout << \" expected : \" << sqrt(static_cast(5))/3U << std::endl;\n std::cout << \" expected : \" << 0.74535599249992989880\n << std::endl;\n std::cout << \" bit_error : \" << static_cast(bit_error) << std::endl;\n\n std::cout.precision(6);\n std::cout << \"float_distance = \" << boost::math::float_distance(0.74535599249992989880, d) << std::endl;\n\n \n }\n\n\n} // int main()\n\n/*`\nThe result of this program on a system with an eight-byte, 64-bit IEEE-754\nconforming floating-point representation for `double` is:\n\n derivative : 0.745355992499951\n\n derivative : 0.745355992499943\n expected : 0.74535599249993\n bit_error : 78\n\n derivative : 0.745355992499930\n expected : 0.745355992499930\n bit_error : 0\n\nThe resulting bit error is 0. This means that the result of the derivative\ncalculation is bit-identical with the double representation of the expected result,\nand this is the best result possible for the built-in type.\n\nThe derivative in this example has a known closed form. There are, however,\ncountless situations in numerical analysis (and not only for numerical deriva-\ntives) for which the calculation at hand does not have a known closed-form\nsolution or for which the closed-form solution is highly inconvenient to use. In\nsuch cases, this technique may be useful.\n\nThis example has shown how multiprecision can be used to add extra digits\nto an ill-conditioned calculation that suffers from precision loss. When the result\nof the multiprecision calculation is converted to a built-in type such as double,\nthe entire precision of the result in double is preserved.\n\n */\n\n/*\n\n Description: Autorun \"J:\\Cpp\\big_number\\Debug\\numerical_derivative_example.exe\"\n derivative : 0.745355992499943\n expected : 0.745355992499930\n expected : 0.745355992499930\n bit_error : 78\n float_distance = 117.000\n derivative : 0.745355992499930\n expected : 0.745355992499930\n expected : 0.745355992499930\n bit_error : 0\n float_distance = 0.000000\n\n */", "meta": {"hexsha": "731604108b81cf7e4a77b958d5942da74013ab80", "size": 7979, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "debian/tests/srcs/math/demo1.cpp", "max_stars_repo_name": "lliurex/boost1.67", "max_stars_repo_head_hexsha": "bab6eba0e7ac4a0232bc0bcab501f1b447ddfdd5", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "debian/tests/srcs/math/demo1.cpp", "max_issues_repo_name": "lliurex/boost1.67", "max_issues_repo_head_hexsha": "bab6eba0e7ac4a0232bc0bcab501f1b447ddfdd5", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "debian/tests/srcs/math/demo1.cpp", "max_forks_repo_name": "lliurex/boost1.67", "max_forks_repo_head_hexsha": "bab6eba0e7ac4a0232bc0bcab501f1b447ddfdd5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9952380952, "max_line_length": 125, "alphanum_fraction": 0.7102393784, "num_tokens": 2116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.8354835432479663, "lm_q1q2_score": 0.7512011186083317}} {"text": "#include \"interpolator.h\"\n#include \n#include \n#include \n\nusing std::vector;\nusing Eigen::VectorXd;\nusing Eigen::MatrixXd;\nusing Eigen::FullPivLU;\nusing Eigen::Map;\n\nnamespace rbf\n{\n\nextern VectorXd solveLinearSystem(const MatrixXd& A, const VectorXd& y);\n\nInterpolator::Interpolator(FunctionType functionType, const double epsilon) :\n functionType(functionType),\n epsilon(epsilon)\n{\n}\n\nvoid Interpolator::reset()\n{\n ys.clear();\n xs.clear();\n w.clear();\n}\n\nvoid Interpolator::addCenterPoint(const double y, const vector& x)\n{\n ys.push_back(y);\n xs.push_back(x);\n}\n\nvoid Interpolator::computeWeights(const bool useRegularization, const double lambda)\n{\n assert(ys.size() == xs.size());\n\n const int dim = ys.size();\n\n MatrixXd O = MatrixXd::Zero(dim, dim);\n VectorXd y = Map(&ys[0], dim);\n\n for (int i = 0; i < dim; ++ i)\n {\n for (int j = 0; j < dim; ++ j)\n {\n O(i, j) = getRbfValue(xs[i], xs[j]);\n }\n }\n\n MatrixXd A;\n VectorXd b;\n if (useRegularization)\n {\n MatrixXd O2 = MatrixXd::Zero(dim * 2, dim);\n for (int i = 0; i < dim; ++ i)\n {\n for (int j = 0; j < dim; ++ j)\n {\n O2(i, j) = O(i, j);\n }\n }\n const double coef = 0.5 * lambda;\n for (int i = 0; i < dim; ++ i)\n {\n O2(i + dim, i) = coef;\n }\n\n VectorXd y2 = VectorXd::Zero(dim * 2);\n for (int i = 0; i < dim; ++ i)\n {\n y2(i) = y(i);\n }\n\n A = O2.transpose() * O2;\n b = O2.transpose() * y2;\n }\n else\n {\n A = O;\n b = y;\n }\n\n const VectorXd x = solveLinearSystem(A, b);\n assert(x.rows() == dim);\n\n w.resize(dim);\n for (int i = 0; i < dim; ++ i)\n {\n w[i] = x(i);\n }\n}\n\ndouble Interpolator::getInterpolatedValue(const vector& x) const\n{\n assert(w.size() == xs.size());\n \n const int dim = w.size();\n\n double result = 0.0;\n for (int i = 0; i < dim; ++ i)\n {\n result += w[i] * getRbfValue(x, xs[i]);\n }\n\n return result;\n}\n\ndouble Interpolator::getRbfValue(const double r) const\n{\n double result;\n switch (functionType)\n {\n case FunctionType::Gaussian:\n result = exp(- pow((epsilon * r), 2.0));\n break;\n case FunctionType::ThinPlateSpline:\n result = r * r * log(r);\n if (isnan(result))\n {\n result = 0.0;\n }\n break;\n case FunctionType::InverseQuadratic:\n result = 1.0 / (1.0 + pow((epsilon * r), 2.0));\n break;\n case FunctionType::BiharmonicSpline:\n result = r;\n break;\n default:\n break;\n }\n return result;\n}\n\ndouble Interpolator::getRbfValue(const vector& xi, const vector& xj) const\n{\n assert (xi.size() == xj.size());\n\n const VectorXd xiVec = Map(&xi[0], xi.size());\n const VectorXd xjVec = Map(&xj[0], xj.size());\n\n return getRbfValue((xjVec - xiVec).norm());\n}\n\nVectorXd solveLinearSystem(const MatrixXd& A, const VectorXd& y)\n{\n FullPivLU lu(A);\n return lu.solve(y);\n}\n\n}\n", "meta": {"hexsha": "fd3160eaecc4989a98220a2939f7e00598e05c4e", "size": 3283, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rbf_interpolator/interpolator.cpp", "max_stars_repo_name": "yuki-koyama/rbf-interpolator", "max_stars_repo_head_hexsha": "5ae1822ba53dcff29768fdfc8f8bb88160c6364f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-05-26T22:28:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:40:18.000Z", "max_issues_repo_path": "rbf_interpolator/interpolator.cpp", "max_issues_repo_name": "yuki-koyama/rbf-interpolator", "max_issues_repo_head_hexsha": "5ae1822ba53dcff29768fdfc8f8bb88160c6364f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-04-11T05:03:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-11T05:05:05.000Z", "max_forks_repo_path": "rbf_interpolator/interpolator.cpp", "max_forks_repo_name": "yuki-koyama/rbf-interpolator", "max_forks_repo_head_hexsha": "5ae1822ba53dcff29768fdfc8f8bb88160c6364f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-03-09T08:32:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T02:40:19.000Z", "avg_line_length": 21.1806451613, "max_line_length": 90, "alphanum_fraction": 0.5254340542, "num_tokens": 920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7510503284543645}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing boost::multiprecision::cpp_int;\ntemplate \nusing bit_generator = boost::random::independent_bits_engine;\n\ntemplate\nE gcd(E a, E b) {\n E zero(0);\n while (b != zero) {\n a = a % b;\n std::swap(a, b);\n }\n return a;\n}\n\ntemplate\nstd::pair\nquotient_remainder(T a, T b) {\n return { a / b, a % b };\n}\n\ntemplate \nstd::pair extended_gcd(E a, E b) {\n E x0(1);\n E x1(0);\n while (b != E(0)) {\n // compute new r and x\n std::pair qr = quotient_remainder(a, b);\n E x2 = x0 - qr.first * x1;\n // shift r and x\n x0 = x1;\n x1 = x2;\n a = b;\n b = qr.second;\n }\n return {x0, a};\n}\n\ntemplate\nconstexpr\ninline\nbool odd(Integer x) {\n return (x & 1) == 1;\n}\n\n\ntemplate\nconstexpr\ninline\nbool even(Integer x) {\n return !odd(x);\n}\n\ntemplate\nconstexpr\ninline\nInteger half(Integer x) {\n // precondition(x >= 0)\n return x >> 1;\n}\n\ntemplate \n// requires (Domain)\nA power_accumulate_semigroup(A r, A a, N n, Op op) {\n // precondition(n >= 0);\n if (n == 0) return r;\n while (true) {\n if (odd(n)) {\n r = op(r, a);\n if (n == 1) return r;\n }\n n = half(n);\n a = op(a, a);\n }\n}\n\n\ntemplate \nMultiplicativeSemigroup power_accumulate_semigroup(MultiplicativeSemigroup r, MultiplicativeSemigroup a, Integer n) {\n // precondition(n >= 0);\n if (n == 0) return r;\n while (true) {\n if (odd(n)) {\n r = r * a;\n if (n == 1) return r;\n }\n n = half(n);\n a = a * a;\n }\n}\n\ntemplate \n// requires (Domain)\nA power_semigroup(A a, N n, Op op) {\n // precondition(n > 0);\n while (!odd(n)) {\n a = op(a, a);\n n = half(n);\n }\n if (n == 1) return a;\n // Auch\n return power_accumulate_semigroup(a, op(a, a), half(N{n - 1}), op);\n}\n\n\ntemplate \nMultiplicativeSemigroup power_semigroup(MultiplicativeSemigroup a, Integer n) {\n // precondition(n > 0);\n while (!odd(n)) {\n a = a * a;\n n = half(n);\n }\n if (n == 1) return a;\n return power_accumulate_semigroup(a, a * a, half(n - 1));\n}\n\n\ntemplate\nstruct modulo_multiply {\n T value;\n modulo_multiply() = default;\n modulo_multiply(const modulo_multiply &) = default;\n modulo_multiply(const T x) : value(x) {}\n T operator()(T x, T y) {\n return (x * y) % value;\n }\n};\n\ntemplate\nstd::pair factorize(T x, T val) {\n // Bad code, can be better\n T k;\n for (k = 0; x % val == 0; x /= val, ++k);\n return std::make_pair(x, k);\n}\n\ntemplate \nbool miller_rabin_test(I n, I q, I k, I w) {\n // precondition n > 1 && n - 1 = 2^kq && q is odd\n \n modulo_multiply mmult(n);\n I x = power_semigroup(w, q, mmult);\n if (x == I(1) || x == n - I(1)) return true;\n for (I i(1); i < k; ++i) {\n \n // invariant x = w^{2^{i-1}q}\n \n x = mmult(x, x);\n if (x == n - I(1)) return true;\n if (x == I(1)) return false;\n }\n return false;\n}\n\n\ntemplate \nN stein_gcd(N m, N n) {\n if (m < N(0)) m = -m;\n if (n < N(0)) n = -n;\n if (m == N(0)) return n;\n if (n == N(0)) return m;\n\n // m > 0 && n > 0\n\n int d_m = 0;\n while (even(m)) { m >>= 1; ++d_m;}\n\n int d_n = 0;\n while (even(n)) { n >>= 1; ++d_n;}\n\n // odd(m) && odd(n)\n\n while (m != n) {\n if (n > m) std::swap(n, m);\n m -= n;\n do m >>= 1; while (even(m));\n }\n\n // m == n\n\n return m << std::min(d_m, d_n);\n}\n\ntemplate\ninline\nInteger random_coprime(Integer x, RandomGenerator& rand) {\n Integer number = rand();\n while (number == 0) number = rand();\n\n Integer gcd_value = gcd(x, number);\n if (gcd_value == Integer{1}) {\n return number;\n }\n ++number;\n return number;\n}\n\ntemplate\nbool check_primarity(Integer n, ProbeGenerator& rand) {\n if (even(n)) { return false; }\n \n std::pair qk = factorize(Integer{n - 1}, Integer{2});\n const constexpr size_t witnesses = 100;\n\n for (size_t i = 0; i < witnesses; ++i) {\n Integer w = random_coprime(n, rand);\n if (!miller_rabin_test(n, qk.first, qk.second, w)) {\n return false;\n }\n }\n return true;\n}\n\ntemplate\nauto probable_prime(PrimarityTest primarity_test, ProbeGenerator& rand, WitnessGenerator& rand_wintness) {\n auto x = rand();\n while (!primarity_test(x, rand_wintness)) {\n x = rand();\n }\n return x;\n}\n\ntemplate\nauto probable_prime(ProbeGenerator& rng, WitnessGenerator& wng) {\n return probable_prime([](const auto &x, auto& rnd) { return check_primarity(x, rnd); }, rng, wng);\n}\n\ntemplate \nI multiplicative_inverse(I a, I n) {\n std::pair p = extended_gcd(a, n);\n if (p.second != I(1)) return I(0);\n if (p.first < I(0)) return p.first + n;\n return p.first;\n}\n\ntemplate\nstruct triple {\n T0 m0;\n T1 m1;\n T2 m2;\n triple(const T0 &m0, const T1 &m1, const T2 &m2) : m0(m0), m1(m1), m2(m2) {}\n};\n\nstruct rsa_keychain {\n cpp_int n = 0;\n cpp_int public_key = 0;\n cpp_int private_key = 0;\n rsa_keychain(const cpp_int &n, const cpp_int &public_key, const cpp_int &private_key) : n(n),\n public_key(public_key),\n private_key(private_key) {}\n size_t block_power_of_2() const\n {\n cpp_int value;\n if (public_key == 0) { value = private_key; }\n else if (private_key == 0) { value = public_key; }\n else { value = std::min(public_key, private_key); }\n const cpp_int m = cpp_int{std::min(value, n)};\n return static_cast(factorize(m, cpp_int{2}).first);\n }\n};\n\ntemplate \nrsa_keychain rsa_key_generation(ProbeGenerator& p_generator, WitnessGenerator& w_generator) {\n typedef cpp_int Integer;\n while(true) {\n Integer p1 = probable_prime(p_generator, w_generator);\n Integer p2 = probable_prime(p_generator, w_generator);\n Integer n = p1 * p2;\n Integer phi = (p1 - 1) * (p2 - 1);\n Integer public_key = random_coprime(phi, p_generator);\n while (public_key >= phi) {\n public_key = random_coprime(phi, p_generator);\n }\n Integer private_key = multiplicative_inverse(public_key, phi);\n if (private_key != 0)\n return rsa_keychain(n, public_key, private_key);\n }\n}\n\n// implement using operator<<\nstd::pair save(const rsa_keychain &rsa_data, const std::string &file_name) {\n auto first = file_name + \".public\";\n std::ofstream public_file(first);\n public_file << std::hex << rsa_data.n << std::endl << rsa_data.public_key;\n auto second = file_name + \".public\";\n std::ofstream private_file(second);\n private_file << std::hex << rsa_data.n << std::endl << rsa_data.private_key;\n return {first, second};\n}\n\n\n/*\ntemplate\nOutputIterator encrypt(uint8_t *first, uint8_t *last, const cpp_int &n, const cpp_int &public_key, OutputIterator out) {\n constexpr size_t block_size = factorize(n, cpp_int{2});\n auto qr = quotient_remainder(size_t{last - first}, block_size);\n for (size_t i = 0; i != qr.first; ++i) {\n cpp_int val = *(uint64_t*)first;\n }\n return out;\n}\n*/\n\ncpp_int crypt(cpp_int val, cpp_int n, cpp_int key) {\n return power_semigroup(val, key, modulo_multiply(n));\n}\n\nint main() {\n //boost::mt19937 rng(42);\n bit_generator probe_generator, witness_generator;\n auto rsa_triple = rsa_key_generation(probe_generator, witness_generator);\n cpp_int value = 65;\n auto encrypted = crypt(value, rsa_triple.n, rsa_triple.public_key);\n auto decrypted = crypt(encrypted, rsa_triple.n, rsa_triple.private_key);\n std::cout << decrypted << std::endl;\n\n}\n", "meta": {"hexsha": "4454eceef36262f4f25549072e3938bff827abd9", "size": 8499, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "Megalitum/rsa", "max_stars_repo_head_hexsha": "bd32b470c1ecd13523e93a4ef270195cb58550d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-24T14:03:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-04T21:50:21.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "Megalitum/rsa", "max_issues_repo_head_hexsha": "bd32b470c1ecd13523e93a4ef270195cb58550d4", "max_issues_repo_licenses": ["MIT"], "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": "Megalitum/rsa", "max_forks_repo_head_hexsha": "bd32b470c1ecd13523e93a4ef270195cb58550d4", "max_forks_repo_licenses": ["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.0705521472, "max_line_length": 120, "alphanum_fraction": 0.6091304859, "num_tokens": 2479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.750926010527023}} {"text": "#include \"Arduino.h\"\r\n#include \"math.h\"\r\n#include \"navduino.h\"\r\n#include \"wgs84.h\"\r\n#include \"eigen.h\"\r\n#include \r\n#include \r\n\r\n\r\n\r\n\r\nusing namespace Eigen;\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n This function converts a vector of euler angles into a Direction Cosine\r\n Matrix (DCM) given a rotation and frame sequence. In the case of this\r\n function, the returned DCM maps vectors from one coordinate frame (either\r\n North-East-Down (NED) or body frame) into the other. This is done by\r\n multiplying the DCM with the vector to be rotated: v_body = DCM * v_NED.\r\n\r\n https://en.wikipedia.org/wiki/Rotation_matrix\r\n https://en.wikipedia.org/wiki/Axes_conventions\r\n https://en.wikipedia.org/wiki/Euler_angles\r\n \r\n Arguments:\r\n ----------\r\n * const Vector3f& angles - Vector of euler angles to describe the rotation\r\n * const bool& angle_unit - Unit of the euler angles (rad or degrees)\r\n * const bool& NED_to_body - Rotate either to or from the NED frame\r\n * const int& rotation_sequence - The order in which the euler angles are applied\r\n to the rotation. 321 is the standard rotation\r\n sequence for aerial navigation\r\n \r\n Returns:\r\n --------\r\n * Matrix3f dcm - Direction cosine matrix (rotation matix)\r\n*/\r\nMatrix3f angle2dcm(const Vector3f& angles, const bool& angle_unit, const bool& NED_to_body, const int& rotation_sequence)\r\n{\r\n float roll;\r\n float pitch;\r\n float yaw;\r\n\r\n if (angle_unit == DEGREES)\r\n {\r\n roll = deg2rad(angles(0));\r\n pitch = deg2rad(angles(1));\r\n yaw = deg2rad(angles(2));\r\n }\r\n else\r\n {\r\n roll = angles(0);\r\n pitch = angles(1);\r\n yaw = angles(2);\r\n }\r\n\r\n Matrix3f R1(3, 3);\r\n Matrix3f R2(3, 3);\r\n Matrix3f R3(3, 3);\r\n\r\n R1 << 1, 0, 0,\r\n 0, cos(roll), sin(roll),\r\n 0, -sin(roll), cos(roll);\r\n\r\n R2 << cos(pitch), 0, -sin(pitch),\r\n 0, 1, 0,\r\n sin(pitch), 0, cos(pitch);\r\n\r\n R3 << cos(yaw), sin(yaw), 0,\r\n -sin(yaw), cos(yaw), 0,\r\n 0, 0, 1;\r\n\r\n Matrix3f dcm(3, 3);\r\n\r\n // Note that multiplication of the matrices are opposite to the\r\n // rotation sequence due to how matrix multiplication works\r\n if (rotation_sequence == 321)\r\n dcm = R1 * R2 * R3;\r\n else if (rotation_sequence == 312)\r\n dcm = R2 * R1 * R3;\r\n else if (rotation_sequence == 231)\r\n dcm = R1 * R3 * R2;\r\n else if (rotation_sequence == 213)\r\n dcm = R3 * R1 * R2;\r\n else if (rotation_sequence == 132)\r\n dcm = R2 * R3 * R1;\r\n else if (rotation_sequence == 123)\r\n dcm = R3 * R2 * R1;\r\n else\r\n dcm = R1 * R2 * R3;\r\n\r\n if (!NED_to_body)\r\n return dcm.transpose();\r\n\r\n return dcm;\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n This function converts a Direction Cosine Matrix (DCM) into the \r\n corresponding euler angles.\r\n\r\n https://en.wikipedia.org/wiki/Rotation_matrix\r\n https://en.wikipedia.org/wiki/Axes_conventions\r\n https://en.wikipedia.org/wiki/Euler_angles\r\n\r\n Arguments:\r\n ----------\r\n * const Matrix3f& dcm - Direction cosine matrix (rotation matix)\r\n * const bool& angle_unit - Unit of the euler angles (rad or degrees)\r\n * const bool& NED_to_body - Rotate either to or from the NED frame\r\n * const int& rotation_sequence - The order in which the euler angles are applied\r\n to the rotation. 321 is the standard rotation\r\n sequence for aerial navigation\r\n\r\n Returns:\r\n --------\r\n * Vector3f angles - Vector of euler angles to describe the rotation\r\n*/\r\nVector3f dcm2angle(const Matrix3f& dcm, const bool& angle_unit, const bool& NED_to_body, const int& rotation_sequence)\r\n{\r\n Vector3f angles;\r\n\r\n if (rotation_sequence == 321)\r\n {\r\n if (NED_to_body)\r\n {\r\n angles << atan2(dcm(1, 2), dcm(2, 2)), // Roll\r\n -asin(dcm(0, 2)), // Pitch\r\n atan2(dcm(0, 1), dcm(0, 0)); // Yaw\r\n }\r\n else\r\n {\r\n angles << atan2(dcm(2, 1), dcm(2, 2)), // Roll\r\n -asin(dcm(2, 0)), // Pitch\r\n atan2(dcm(1, 0), dcm(0, 0)); // Yaw\r\n }\r\n }\r\n\r\n if (angle_unit == DEGREES)\r\n {\r\n angles(0) = rad2deg(angles(0));\r\n angles(1) = rad2deg(angles(1));\r\n angles(2) = rad2deg(angles(2));\r\n }\r\n\r\n return angles;\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Convert a sequence of euler angles to an equivalent unit quaternion.\r\n\r\n https://eater.net/quaternions\r\n https://en.wikipedia.org/wiki/Axes_conventions\r\n https://en.wikipedia.org/wiki/Euler_angles\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& angles - Vector of euler angles to describe the rotation\r\n * const bool& angle_unit - Unit of the euler angles (rad or degrees)\r\n * const bool& NED_to_body - Rotate either to or from the NED frame\r\n * const int& rotation_sequence - The order in which the euler angles are applied\r\n to the rotation. 321 is the standard rotation\r\n sequence for aerial navigation\r\n\r\n Returns:\r\n --------\r\n * Quaternionf quat - Quaternion that describes the rotation\r\n*/\r\nQuaternionf angle2quat(const Vector3f& angles, const bool& angle_unit, const bool& NED_to_body, const int& rotation_sequence)\r\n{\r\n Quaternionf quat(angle2dcm(angles, angle_unit, NED_to_body, rotation_sequence));\r\n return quat;\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Convert a unit quaternion to the equivalent sequence of euler angles\r\n about the rotation_sequence axes.\r\n\r\n https://eater.net/quaternions\r\n https://en.wikipedia.org/wiki/Axes_conventions\r\n https://en.wikipedia.org/wiki/Euler_angles\r\n\r\n Arguments:\r\n ----------\r\n * const Quaternionf quat - Quaternion that describes the rotation\r\n * const bool& angle_unit - Unit of the euler angles (rad or degrees)\r\n * const bool& NED_to_body - Rotate either to or from the NED frame\r\n * const int& rotation_sequence - The order in which the euler angles are applied\r\n to the rotation. 321 is the standard rotation\r\n sequence for aerial navigation\r\n\r\n Returns:\r\n --------\r\n * Vector3f& angles - Vector of euler angles to describe the rotation\r\n*/\r\nVector3f quat2angle(const Quaternionf& quat, const bool& angle_unit, const bool& NED_to_body, const int& rotation_sequence)\r\n{\r\n return dcm2angle(quat.toRotationMatrix(), angle_unit, NED_to_body, rotation_sequence);\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Convert a single unit quaternion to one DCM.\r\n\r\n https://eater.net/quaternions\r\n https://en.wikipedia.org/wiki/Rotation_matrix\r\n https://en.wikipedia.org/wiki/Axes_conventions\r\n\r\n Arguments:\r\n ----------\r\n * const Quaternionf quat - Quaternion that describes the rotation\r\n * const bool& angle_unit - Unit of the euler angles (rad or degrees)\r\n * const bool& NED_to_body - Rotate either to or from the NED frame\r\n * const int& rotation_sequence - The order in which the euler angles are applied\r\n to the rotation. 321 is the standard rotation\r\n sequence for aerial navigation\r\n\r\n Returns:\r\n --------\r\n * Matrix3f& dcm - Rotates vectors from one coordinate frame to the other\r\n*/\r\nMatrix3f quat2dcm(const Quaternionf& quat)\r\n{\r\n return quat.toRotationMatrix();\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Convert a DCM to a unit quaternion.\r\n\r\n https://eater.net/quaternions\r\n https://en.wikipedia.org/wiki/Rotation_matrix\r\n https://en.wikipedia.org/wiki/Axes_conventions\r\n\r\n Arguments:\r\n ----------\r\n * const Matrix3f& dcm - Direction cosine matrix (rotation matix)\r\n * const bool& angle_unit - Unit of the euler angles (rad or degrees)\r\n * const bool& NED_to_body - Rotate either to or from the NED frame\r\n * const int& rotation_sequence - The order in which the euler angles are applied\r\n to the rotation. 321 is the standard rotation\r\n sequence for aerial navigation\r\n\r\n Returns:\r\n --------\r\n * Quaternionf quat - Quaternion that describes the rotation\r\n*/\r\nQuaternionf dcm2quat(const Matrix3f& dcm)\r\n{\r\n Quaternionf quat(dcm);\r\n return quat;\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Convert a Rodrigues rotation vector to a DCM.\r\n\r\n **NOTE: The Rodrigues vector's rotation angle must be in RADIANS.**\r\n\r\n https://courses.cs.duke.edu/fall13/compsci527/notes/rodrigues.pdf\r\n https://en.wikipedia.org/wiki/Rotation_matrix\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& vec - Rodrigues rotation vector\r\n\r\n Returns:\r\n --------\r\n * Matrix3f dcm - Direction cosine matrix (rotation matix)\r\n*/\r\nMatrix3f vec2dcm(const Vector3f& vec)\r\n{\r\n float theta = vec.norm();\r\n Vector3f axis = vec / theta;\r\n\r\n AngleAxisf angAxis(theta, axis);\r\n return angAxis.toRotationMatrix();\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Convert a DCM to a Rodrigues rotation vector.\r\n\r\n https://courses.cs.duke.edu/fall13/compsci527/notes/rodrigues.pdf\r\n https://en.wikipedia.org/wiki/Rotation_matrix\r\n\r\n Arguments:\r\n ----------\r\n * const Matrix3f& dcm - Direction cosine matrix (rotation matix)\r\n\r\n Returns:\r\n --------\r\n * Vector3f vec - Rodrigues rotation vector (rotation angle is in RADIANS)\r\n*/\r\nVector3f dcm2vec(const Matrix3f& dcm)\r\n{\r\n AngleAxisf angAxis(dcm);\r\n return angAxis.angle() * angAxis.axis();\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Convert a Rodrigues rotation vector to a quaternion.\r\n\r\n **NOTE: The Rodrigues vector's rotation angle must be in RADIANS.**\r\n\r\n https://courses.cs.duke.edu/fall13/compsci527/notes/rodrigues.pdf\r\n https://eater.net/quaternions\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& vec - Rodrigues rotation vector\r\n\r\n Returns:\r\n --------\r\n * Quaternionf quat - Quaternion that describes the rotation\r\n*/\r\nQuaternionf vec2quat(const Vector3f& vec)\r\n{\r\n return dcm2quat(vec2dcm(vec));\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Convert a quaternion to a Rodrigues rotation vector.\r\n\r\n https://courses.cs.duke.edu/fall13/compsci527/notes/rodrigues.pdf\r\n https://eater.net/quaternions\r\n\r\n Arguments:\r\n ----------\r\n * const Quaternionf& quat - Quaternion that describes the rotation\r\n\r\n Returns:\r\n --------\r\n * Vector3f vec - Rodrigues rotation vector (rotation angle is in RADIANS)\r\n*/\r\nVector3f quat2vec(const Quaternionf& quat)\r\n{\r\n AngleAxisf angAxis(quat);\r\n return angAxis.angle() * angAxis.axis();\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Convert a Rodrigues rotation vector to a vector of euler angles.\r\n\r\n **NOTE: The Rodrigues vector's rotation angle must be in RADIANS.**\r\n\r\n https://courses.cs.duke.edu/fall13/compsci527/notes/rodrigues.pdf\r\n https://en.wikipedia.org/wiki/Axes_conventions\r\n https://en.wikipedia.org/wiki/Euler_angles\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& vec - Rodrigues rotation vector\r\n * const bool& angle_unit - Unit of the euler angles (rad or degrees)\r\n * const bool& NED_to_body - Rotate either to or from the NED frame\r\n * const int& rotation_sequence - The order in which the euler angles are applied\r\n to the rotation. 321 is the standard rotation\r\n sequence for aerial navigation\r\n\r\n Returns:\r\n --------\r\n * Vector3f angles - Vector of euler angles\r\n*/\r\nVector3f vec2angle(const Vector3f& vec, const bool& angle_unit, const bool& NED_to_body, const int& rotation_sequence)\r\n{\r\n return dcm2angle(vec2dcm(vec), angle_unit, NED_to_body, rotation_sequence);\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Convert a vector of euler angles to a Rodrigues rotation vector.\r\n\r\n https://courses.cs.duke.edu/fall13/compsci527/notes/rodrigues.pdf\r\n https://en.wikipedia.org/wiki/Axes_conventions\r\n https://en.wikipedia.org/wiki/Euler_angles\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& angles - Vector of euler angles\r\n * const bool& angle_unit - Unit of the euler angles (rad or degrees)\r\n * const bool& NED_to_body - Rotate either to or from the NED frame\r\n * const int& rotation_sequence - The order in which the euler angles are applied\r\n to the rotation. 321 is the standard rotation\r\n sequence for aerial navigation\r\n\r\n Returns:\r\n --------\r\n * Vector3f vec - Rodrigues rotation vector (rotation angle is in RADIANS)\r\n*/\r\nVector3f angle2vec(const Vector3f& angles, const bool& angle_unit, const bool& NED_to_body, const int& rotation_sequence)\r\n{\r\n return dcm2vec(angle2dcm(angles, angle_unit, NED_to_body, rotation_sequence));\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Calculate Earth's geocentric radius at a given geodetic latitude in\r\n meters. \"The geocentric radius is the distance from the Earth's\r\n center to a point on the spheroid surface at geodetic latitude\".\r\n\r\n https://en.wikipedia.org/wiki/Earth_radius\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const float& _lat - Angle of latitude\r\n * const bool& angle_unit - Unit of the latitude angle (rad or degrees)\r\n \r\n Returns:\r\n --------\r\n * float radius - Earth's geocentric radius in meters at a given latitude in meters\r\n*/\r\nfloat earthGeoRad(const float& _lat, const bool& angle_unit)\r\n{\r\n float lat = _lat;\r\n\r\n if (angle_unit == DEGREES)\r\n lat = deg2rad(lat);\r\n\r\n float num = pow(a_sqrd * cos(lat), 2) + pow(b_sqrd * sin(lat), 2);\r\n float den = pow(a * cos(lat), 2) + pow(b * sin(lat), 2);\r\n\r\n return sqrt(num / den);\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Calculate Earth's radius of curvature in the prime vertical (East -\r\n West) - denoted as N - and meridian (North - South) - denoted as\r\n M - at a given latitude.\r\n\r\n https://en.wikipedia.org/wiki/Radius_of_curvature\r\n https://en.wikipedia.org/wiki/Earth_radius\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const float& _lat - Angle of latitude\r\n * const bool& angle_unit - Unit of the latitude angle (rad or degrees)\r\n\r\n Returns:\r\n --------\r\n * Vector2f radii - Earth's radii of curvature { N, M } in meters at a given latitude\r\n*/\r\nVector2f earthRad(const float& _lat, const bool& angle_unit)\r\n{\r\n float lat = _lat;\r\n\r\n if (angle_unit == DEGREES)\r\n lat = deg2rad(lat);\r\n\r\n float R_N = a / sqrt(1 - (ecc_sqrd * pow(sin(lat), 2)));\r\n float R_M = (a * (1 - ecc_sqrd)) / pow(1 - (ecc_sqrd * pow(sin(lat), 2)), 1.5);\r\n\r\n Vector2f radii;\r\n radii << R_N, // Earth's prime-vertical radius of curvature\r\n R_M; // Earth's meridional radius of curvature\r\n\r\n return radii;\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Calculate azimuthal radius at a given latitude. This is the\r\n Earth's radius of cuvature at a given latitude in the\r\n direction of a given asimuth.\r\n\r\n https://en.wikipedia.org/wiki/Radius_of_curvature\r\n https://en.wikipedia.org/wiki/Earth_radius\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const float& _lat - Angle of latitude\r\n * const bool& angle_unit - Unit of the latitude angle (rad or degrees)\r\n\r\n Returns:\r\n --------\r\n * float radius - Earth's azimuthal radius in meters at a given latitude and azimuth\r\n*/\r\nfloat earthAzimRad(const float& lat, const float& _azimuth, const bool& angle_unit)\r\n{\r\n float azimuth = _azimuth;\r\n\r\n if (angle_unit == DEGREES)\r\n azimuth = deg2rad(azimuth);\r\n\r\n Vector2f eradvec = earthRad(lat, angle_unit);\r\n float N = eradvec(0);\r\n float M = eradvec(1);\r\n\r\n return 1 / ((pow(cos(azimuth), 2) / M) + (pow(sin(azimuth), 2) / N));\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Calculate Earth's angular velocity in m/s resolved in the NED frame at a given\r\n latitude.\r\n\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const float& _lat - Angle of latitude\r\n * const bool& angle_unit - Unit of the latitude angle (rad or degrees)\r\n\r\n Returns:\r\n --------\r\n * Vector3f e - Earth's angular velocity resolved in the NED frame at a given latitude\r\n*/\r\nVector3f earthRate(const float& _lat, const bool& angle_unit)\r\n{\r\n float lat = _lat;\r\n\r\n if (angle_unit == DEGREES)\r\n lat = deg2rad(lat);\r\n\r\n Vector3f e;\r\n e << omega_E * cos(lat),\r\n 0,\r\n -omega_E * sin(lat);\r\n\r\n return e;\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Calculate the latitude, longitude, and altitude (LLA) angular rates\r\n given the locally tangent velocity in the NED frame and latitude.\r\n\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& vned - Velocity vector in m/s in the NED frame\r\n * const Vector3f& lla - LLA coordinate (altitude in meters)\r\n * const bool& angle_unit - Unit of the latitude and longitude angles (rad\r\n or degrees) (this also affects the output units\r\n (rad/s or degrees/s)\r\n\r\n Returns:\r\n --------\r\n * Vector3f lla_dot - LLA angular rates given the locally tangent velocity\r\n in the NED frame and latitude\r\n*/\r\nVector3f llaRate(const Vector3f& vned, const Vector3f& lla, const bool& angle_unit)\r\n{\r\n float VN = vned(0);\r\n float VE = vned(1);\r\n float VD = vned(2);\r\n\r\n float lat = lla(0);\r\n float alt = lla(2);\r\n\r\n Vector2f eradvec = earthRad(lat, angle_unit);\r\n float Rew = eradvec(0);\r\n float Rns = eradvec(1);\r\n\r\n if (angle_unit == DEGREES)\r\n lat = deg2rad(lat);\r\n\r\n Vector3f lla_dot;\r\n\r\n if (angle_unit == RADIANS)\r\n {\r\n lla_dot << VN / (Rns + alt),\r\n VE / (Rew + alt) / cos(lat),\r\n -VD;\r\n }\r\n else\r\n {\r\n lla_dot << rad2deg(VN / (Rns + alt)),\r\n rad2deg(VE / (Rew + alt) / cos(lat)),\r\n -VD;\r\n }\r\n\r\n return lla_dot;\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Calculate the navigation/transport angular rates given the locally tangent\r\n velocity in the NED frame and latitude. The navigation/transport rate is\r\n the angular velocity of the NED frame relative to the ECEF frame.\r\n\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& vned - Velocity vector in m/s in the NED frame\r\n * const Vector3f& lla - LLA coordinate (altitude in meters)\r\n * const bool& angle_unit - Unit of the latitude and longitude angles (rad\r\n or degrees) (this also affects the output units\r\n (rad/s or degrees/s)\r\n\r\n Returns:\r\n --------\r\n * Vector3f rho - Navigation/transport angular rates in the ECEF frame given\r\n the locally tangent velocity in the NED frame and latitude\r\n*/\r\nVector3f navRate(const Vector3f& vned, const Vector3f& lla, const bool& angle_unit)\r\n{\r\n float VN = vned(0);\r\n float VE = vned(1);\r\n\r\n float lat = lla(0);\r\n float alt = lla(2);\r\n\r\n Vector2f eradvec = earthRad(lat, angle_unit);\r\n float Rew = eradvec(0);\r\n float Rns = eradvec(1);\r\n\r\n if (angle_unit == DEGREES)\r\n lat = deg2rad(lat);\r\n\r\n Vector3f rho;\r\n\r\n if (angle_unit == RADIANS)\r\n {\r\n rho << VE / (Rew + alt),\r\n -VN / (Rns + alt),\r\n -VE * tan(lat) / (Rew + alt);\r\n }\r\n else\r\n {\r\n rho << rad2deg(VE / (Rew + alt)),\r\n rad2deg(-VN / (Rns + alt)),\r\n rad2deg(-VE * tan(lat) / (Rew + alt));\r\n }\r\n\r\n return rho;\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Convert a LLA coordinate to an ECEF coordinate.\r\n\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n https://en.wikipedia.org/wiki/Earth-centered,_Earth-fixed_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& lla - LLA coordinate (altitude in meters)\r\n * const bool& angle_unit - Unit of the latitude and longitude angles (rad\r\n or degrees)\r\n\r\n Returns:\r\n --------\r\n * Vector3f ecef - ECEF coordinate in meters\r\n*/\r\nVector3f lla2ecef(const Vector3f& lla, const bool& angle_unit)\r\n{\r\n float lat = lla(0);\r\n float lon = lla(1);\r\n float alt = lla(2);\r\n\r\n Vector2f eradvec = earthRad(lat, angle_unit);\r\n float Rew = eradvec(0);\r\n\r\n if (angle_unit == DEGREES)\r\n {\r\n lat = deg2rad(lat);\r\n lon = deg2rad(lon);\r\n }\r\n\r\n Vector3f ecef;\r\n\r\n ecef << (Rew + alt) * cos(lat) * cos(lon),\r\n (Rew + alt)* cos(lat)* sin(lon),\r\n ((1 - ecc_sqrd) * Rew + alt)* sin(lat);\r\n\r\n return ecef;\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Convert an ECEF coordinate to a LLA coordinate.\r\n\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n https://en.wikipedia.org/wiki/Earth-centered,_Earth-fixed_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& ecef - ECEF coordinate in meters\r\n * const bool& angle_unit - Unit of the latitude and longitude angles (rad\r\n or degrees)\r\n\r\n Returns:\r\n --------\r\n * Vector3f lla - LLA coordinate (altitude in meters)\r\n*/\r\nVector3f ecef2lla(const Vector3f& ecef, const bool& angle_unit)\r\n{\r\n float x = ecef(0);\r\n float y = ecef(1);\r\n float z = ecef(2);\r\n\r\n float x_sqrd = pow(x, 2);\r\n float y_sqrd = pow(y, 2);\r\n float z_sqrd = pow(z, 2);\r\n\r\n float lon = atan2(y, x);\r\n\r\n float p = sqrt(x_sqrd + y_sqrd);\r\n float p_sqrd = pow(p, 2);\r\n float F = 54 * b_sqrd * z_sqrd;\r\n float G = p_sqrd + ((1 - ecc_sqrd) * z_sqrd) - (ecc_sqrd * (a_sqrd - b_sqrd));\r\n float G_sqrd = pow(G, 2);\r\n float c = (pow(ecc, 4) * F * p_sqrd) / pow(G, 3);\r\n float c_sqrd = pow(c, 2);\r\n float s = pow(1 + c + sqrt(c_sqrd + (2 * c)), 1.5);\r\n float k = s + 1 + (1 / s);\r\n float k_sqrd = pow(k, 2);\r\n float P = F / (3 * k_sqrd * G_sqrd);\r\n float Q = sqrt(1 + (2 * pow(ecc, 4) * P));\r\n float r0 = ((-P * ecc_sqrd * p) / (1 + Q)) + sqrt((0.5 * a_sqrd * (1 + (1 / Q))) - ((P * (1 - ecc_sqrd) * z_sqrd) / (Q * (1 + Q))) - (0.5 * P * p_sqrd));\r\n float U = sqrt(pow(p - (ecc_sqrd * r0), 2) + z_sqrd);\r\n float V = sqrt(pow(p - (ecc_sqrd * r0), 2) + ((1 - ecc_sqrd) * z_sqrd));\r\n float z0 = (b_sqrd * z) / (a * V);\r\n\r\n float h = U * (1 - (b_sqrd / (a * V)));\r\n float lat = atan2(z + (ecc_prime_sqrd * z0), p);\r\n\r\n if (angle_unit == DEGREES)\r\n {\r\n lat = rad2deg(lat);\r\n lon = rad2deg(lon);\r\n }\r\n\r\n Vector3f lla;\r\n lla << lat,\r\n lon,\r\n h;\r\n\r\n return lla;\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Find the direction cosine matrix that describes the rotation from the ECEF\r\n coordinate frame to the NED frame given a lat/lon/alt location.\r\n\r\n https://www.mathworks.com/help/aeroblks/directioncosinematrixeceftoned.html\r\n https://en.wikipedia.org/wiki/Rotation_matrix\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n https://en.wikipedia.org/wiki/Earth-centered,_Earth-fixed_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& lla - LLA coordinate (altitude in meters)\r\n * const bool& angle_unit - Unit of the latitude and longitude angles (rad\r\n or degrees)\r\n\r\n Returns:\r\n --------\r\n * Matrix3f C - \r\n*/\r\nMatrix3f ecef2ned_dcm(const Vector3f& lla, const bool& angle_unit)\r\n{\r\n float lat = lla(0);\r\n float lon = lla(1);\r\n\r\n if (angle_unit == DEGREES)\r\n {\r\n lat = deg2rad(lat);\r\n lon = deg2rad(lon);\r\n }\r\n\r\n Matrix3f C;\r\n\r\n C(0, 0) = -sin(lat) * cos(lon);\r\n C(0, 1) = -sin(lat) * sin(lon);\r\n C(0, 2) = cos(lat);\r\n\r\n C(1, 0) = -sin(lon);\r\n C(1, 1) = cos(lon);\r\n C(1, 2) = 0;\r\n\r\n C(2, 0) = -cos(lat) * cos(lon);\r\n C(2, 1) = -cos(lat) * sin(lon);\r\n C(2, 2) = -sin(lat);\r\n\r\n return C;\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Convert an ECEF coordinate to a NED coordinate.\r\n\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n https://en.wikipedia.org/wiki/Earth-centered,_Earth-fixed_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& ecef - ECEF coordinate in meters\r\n * const Vector3f& lla_ref - LLA coordinate of the NED frame origin (altitude in meters)\r\n * const bool& angle_unit - Unit of the latitude and longitude angles (rad\r\n or degrees)\r\n\r\n Returns:\r\n --------\r\n * Vector3f ned - NED coordinate in meters\r\n*/\r\nVector3f ecef2ned(const Vector3f& ecef, const Vector3f& lla_ref, const bool& angle_unit)\r\n{\r\n Vector3f ecef_ref = lla2ecef(lla_ref, angle_unit);\r\n Matrix3f C = ecef2ned_dcm(lla_ref, angle_unit);\r\n\r\n return C * (ecef - ecef_ref);\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Convert a LLA coordinate to a NED coordinate.\r\n\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& lla - LLA coordinate (altitude in meters)\r\n * const Vector3f& lla_ref - LLA coordinate of the NED frame origin (altitude in meters)\r\n * const bool& angle_unit - Unit of the latitude and longitude angles (rad\r\n or degrees)\r\n\r\n Returns:\r\n --------\r\n * Vector3f ned - NED coordinate in meters\r\n*/\r\nVector3f lla2ned(const Vector3f& lla, const Vector3f& lla_ref, const bool& angle_unit)\r\n{\r\n Vector3f ecef = lla2ecef(lla, angle_unit);\r\n Vector3f ned = ecef2ned(ecef, lla_ref, angle_unit);\r\n\r\n return ned;\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Convert a NED coordinate to an ECEF coordinate.\r\n\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n https://en.wikipedia.org/wiki/Earth-centered,_Earth-fixed_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& ned - NED coordinate in meters\r\n * const Vector3f& lla_ref - LLA coordinate of the NED frame origin (altitude in meters)\r\n * const bool& angle_unit - Unit of the latitude and longitude angles (rad\r\n or degrees)\r\n\r\n Returns:\r\n --------\r\n * Vector3f ecef - ECEF coordinate in meters\r\n*/\r\nVector3f ned2ecef(const Vector3f& ned, const Vector3f& lla_ref, const bool& angle_unit)\r\n{\r\n float lat_ref = lla_ref(0);\r\n float lon_ref = lla_ref(1);\r\n\r\n if (angle_unit == DEGREES)\r\n {\r\n lat_ref = deg2rad(lat_ref);\r\n lon_ref = deg2rad(lon_ref);\r\n }\r\n\r\n Matrix3f C(3, 3);\r\n\r\n C(0, 0) = -sin(lat_ref) * cos(lon_ref);\r\n C(0, 1) = -sin(lat_ref) * sin(lon_ref);\r\n C(0, 2) = cos(lat_ref);\r\n\r\n C(1, 0) = -sin(lon_ref);\r\n C(1, 1) = cos(lon_ref);\r\n C(1, 2) = 0;\r\n\r\n C(2, 0) = -cos(lat_ref) * cos(lon_ref);\r\n C(2, 1) = -cos(lat_ref) * sin(lon_ref);\r\n C(2, 2) = -sin(lat_ref);\r\n\r\n Vector3f ecef;\r\n ecef = C.transpose() * ned;\r\n\r\n return ecef;\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Convert a NED coordinate to a LLA coordinate.\r\n\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& ned - NED coordinate in meters\r\n * const Vector3f& lla_ref - LLA coordinate of the NED frame origin (altitude in meters)\r\n * const bool& angle_unit - Unit of the latitude and longitude angles (rad\r\n or degrees)\r\n\r\n Returns:\r\n --------\r\n * Vector3f lla - LLA coordinate (altitude in meters)\r\n*/\r\nVector3f ned2lla(const Vector3f& ned, const Vector3f& lla_ref, const bool& angle_unit)\r\n{\r\n Vector3f ecef = ned2ecef(ned, lla_ref, angle_unit);\r\n Vector3f ecef_ref = lla2ecef(lla_ref, angle_unit);\r\n ecef += ecef_ref;\r\n\r\n Vector3f lla = ecef2lla(ecef, angle_unit);\r\n\r\n return lla;\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Create a 4x4 pose matrix that can be used to apply an affine transform of a\r\n 3 dimensional vector/point from one coordinate frame to another. The two\r\n coordinate frames do not need to be colocated.\r\n\r\n https://en.wikipedia.org/wiki/Affine_transformation\r\n\r\n Arguments:\r\n ----------\r\n * const Matrix3f& dcm - Direction cosine matrix that describes the rotation\r\n between the two coordinate frames\r\n * const Vector3f& t - Translation vector between the origins of the two\r\n coordinate frames (unit of distance is arbitrary - \r\n up to the user to decide)\r\n\r\n Returns:\r\n --------\r\n * Matrix4f poseMatrix - 4x4 pose matrix for affine coordinate frame transforms\r\n*/\r\nMatrix4f poseMat(const Matrix3f& dcm, const Vector3f& t)\r\n{\r\n Matrix4f poseMatrix;\r\n poseMatrix << 0, 0, 0, 0,\r\n 0, 0, 0, 0,\r\n 0, 0, 0, 0,\r\n 0, 0, 0, 0;\r\n poseMatrix(seq(0, 2), seq(0, 2)) << dcm;\r\n poseMatrix(seq(0, 2), 3) << t;\r\n poseMatrix(3, 3) = 1;\r\n\r\n return poseMatrix;\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Extract the DCM from a given pose matrix.\r\n\r\n https://en.wikipedia.org/wiki/Affine_transformation\r\n https://en.wikipedia.org/wiki/Rotation_matrix\r\n\r\n Arguments:\r\n ----------\r\n * const Matrix4f& poseMatrix - 4x4 pose matrix for affine coordinate frame\r\n transforms\r\n\r\n Returns:\r\n --------\r\n * Matrix3f dcm - DCM extracted from pose matrix\r\n*/\r\nMatrix3f pose2dcm(const Matrix4f& poseMatrix)\r\n{\r\n Matrix3f dcm;\r\n dcm << poseMatrix(seq(0, 2), seq(0, 2));\r\n\r\n return dcm;\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Extract translation vector from a given pose matrix.\r\n\r\n https://en.wikipedia.org/wiki/Affine_transformation\r\n\r\n Arguments:\r\n ----------\r\n * const Matrix4f& poseMatrix - 4x4 pose matrix for affine coordinate frame\r\n transforms\r\n\r\n Returns:\r\n --------\r\n * Vector3f t - Translation vector extracted from pose matrix\r\n*/\r\nVector3f pose2t(const Matrix4f& poseMatrix)\r\n{\r\n Vector3f t;\r\n t << poseMatrix(seq(0, 2), 3);\r\n\r\n return t;\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Create a reversed 4x4 pose matrix.\r\n\r\n https://en.wikipedia.org/wiki/Affine_transformation\r\n\r\n Arguments:\r\n ----------\r\n * const Matrix4f& poseMatrix - 4x4 pose matrix for affine coordinate frame\r\n transforms\r\n\r\n Returns:\r\n --------\r\n * Matrix4f poseMatrix - Reversed 4x4 pose matrix for affine coordinate frame\r\n transforms\r\n*/\r\nMatrix4f reversePoseMat(const Matrix4f& poseMatrix)\r\n{\r\n Matrix3f dcm = pose2dcm(poseMatrix);\r\n Vector3f t = pose2t(poseMatrix);\r\n\r\n return poseMat(dcm.transpose(), dcm.transpose() * -t);\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Compute the matrix derivative of the given pose matrix w.r.t the given variable.\r\n The possible variables include:\r\n * dRx - w.r.t. rotation around the x axis\r\n * dRy - w.r.t. rotation around the y axis\r\n * dRz - w.r.t. rotation around the z axis\r\n * dtx - w.r.t. translation around the x axis\r\n * dty - w.r.t. translation around the y axis\r\n * dtz - w.r.t. translation around the z axis\r\n \r\n This operation is often used when constructing Jacobian matrices for optimization\r\n problems (i.e. least squares/GN optimization)\r\n\r\n https://en.wikipedia.org/wiki/Affine_transformation\r\n https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant\r\n https://en.wikipedia.org/wiki/Gauss%E2%80%93Newton_algorithm\r\n\r\n Arguments:\r\n ----------\r\n * const Matrix4f& poseMatrix - 4x4 pose matrix for affine coordinate frame\r\n transforms\r\n * const int& derivType - Variable to take the derivative w.r.t.\r\n\r\n Returns:\r\n --------\r\n * Matrix4f poseMatrix - Pose matrix derivative\r\n*/\r\nMatrix4f poseMatDeriv(const Matrix4f& poseMatrix, const int& derivType)\r\n{\r\n Matrix4f derivPose;\r\n Matrix3f dcm = pose2dcm(poseMatrix);\r\n Vector3f vec;\r\n\r\n switch(derivType)\r\n {\r\n case dRx:\r\n {\r\n vec << 1, 0, 0;\r\n\r\n derivPose(seq(0, 2), seq(0, 2)) << skew(vec) * dcm;\r\n break;\r\n }\r\n\r\n case dRy:\r\n {\r\n vec << 0, 1, 0;\r\n\r\n derivPose(seq(0, 2), seq(0, 2)) << skew(vec) * dcm;\r\n break;\r\n }\r\n\r\n case dRz:\r\n {\r\n vec << 0, 0, 1;\r\n\r\n derivPose(seq(0, 2), seq(0, 2)) << skew(vec) * dcm;\r\n break;\r\n }\r\n\r\n case dtx:\r\n {\r\n vec << 1, 0, 0;\r\n\r\n Matrix4f tempPose;\r\n tempPose(3, seq(0, 2)) << vec;\r\n\r\n derivPose << tempPose * poseMatrix;\r\n break;\r\n }\r\n\r\n case dty:\r\n {\r\n vec << 0, 1, 0;\r\n\r\n Matrix4f tempPose;\r\n tempPose(3, seq(0, 2)) << vec;\r\n\r\n derivPose << tempPose * poseMatrix;\r\n break;\r\n }\r\n\r\n case dtz:\r\n {\r\n vec << 0, 0, 1;\r\n\r\n Matrix4f tempPose;\r\n tempPose(3, seq(0, 2)) << vec;\r\n\r\n derivPose << tempPose * poseMatrix;\r\n break;\r\n }\r\n }\r\n\r\n return derivPose;\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Applies an affine transformation to vector/point x described by the given DCM and\r\n translation vector. This affine transformation converts the vector/point x from\r\n it's initial coordinate frame to another. A common use of this function would be\r\n to convert a 3D point in an airplane's sensor's body frame into the airplane's\r\n body frame (and vice versa).\r\n\r\n https://en.wikipedia.org/wiki/Affine_transformation\r\n\r\n Arguments:\r\n ----------\r\n * const Matrix3f& dcm - Direction cosine matrix that describes the rotation\r\n between the two coordinate frames\r\n * const Vector3f& t - Translation vector between the origins of the two\r\n coordinate frames (unit of distance is arbitrary -\r\n up to the user to decide)\r\n * const Vector3f& x - The vector/point to be transformed\r\n\r\n Returns:\r\n --------\r\n * Vector3f new_x - The vector/point transformed to the new coordinate frame\r\n*/\r\nVector3f transformPt(const Matrix3f& dcm, const Vector3f& t, const Vector3f& x)\r\n{\r\n Vector4f x_1;\r\n x_1 << x;\r\n x_1(3) = 1;\r\n\r\n Vector4f new_x_1 = poseMat(dcm, t) * x_1;\r\n Vector3f new_x = new_x_1(seq(0, 2));\r\n\r\n return new_x;\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Applies an affine transformation to vector/point x described by the given pose\r\n matrix. This affine transformation converts the vector/point x from it's\r\n initial coordinate frame to another. A common use of this function would be\r\n to convert a 3D point in an airplane's sensor's body frame into the airplane's\r\n body frame (and vice versa).\r\n\r\n https://en.wikipedia.org/wiki/Affine_transformation\r\n\r\n Arguments:\r\n ----------\r\n * const Matrix4f& poseMatrix - 4x4 pose matrix for affine coordinate frame\r\n transforms\r\n * const Vector3f& x - The vector/point to be transformed\r\n\r\n Returns:\r\n --------\r\n * Vector3f new_x - The vector/point transformed to the new coordinate frame\r\n*/\r\nVector3f transformPt(const Matrix4f& poseMatrix, const Vector3f& x)\r\n{\r\n Vector4f x_1;\r\n x_1 << x;\r\n x_1(3) = 1;\r\n\r\n Vector4f new_x_1 = poseMatrix * x_1;\r\n Vector3f new_x = new_x_1(seq(0, 2));\r\n\r\n return new_x;\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Make a skew symmetric matrix from a 3 element vector. Skew\r\n symmetric matrices are often used to easily take cross products.\r\n\r\n https://en.wikipedia.org/wiki/Skew-symmetric_matrix\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& w - 3 element vector\r\n\r\n Returns:\r\n --------\r\n * Matrix3f C - Skew symmetric matrix of vector w\r\n*/\r\nMatrix3f skew(const Vector3f& w)\r\n{\r\n Matrix3f C;\r\n\r\n C << 0.0, -w(2), w(1),\r\n w(2), 0.0, -w(0),\r\n -w(1), w(0), 0.0;\r\n\r\n return C;\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Calculate the bearing between two LLA coordinates.\r\n\r\n http://www.movable-type.co.uk/scripts/latlong.html\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& lla_1 - First LLA coordinate (altitude in meters)\r\n * const Vector3f& lla_2 - Second LLA coordinate (altitude in meters)\r\n * const bool& angle_unit - Unit of the latitude, longitude, and bearing\r\n angles (rad or degrees)\r\n\r\n Returns:\r\n --------\r\n * float bearing - The bearing between the two given LLA coordinates\r\n*/\r\nfloat bearingLla(const Vector3f& lla_1, const Vector3f& lla_2, const bool& angle_unit)\r\n{\r\n float lat_1 = lla_1(0);\r\n float lon_1 = lla_1(1);\r\n\r\n float lat_2 = lla_2(0);\r\n float lon_2 = lla_2(1);\r\n\r\n if (angle_unit == DEGREES)\r\n {\r\n lat_1 = deg2rad(lat_1);\r\n lon_1 = deg2rad(lon_1);\r\n\r\n lat_2 = deg2rad(lat_2);\r\n lon_2 = deg2rad(lon_2);\r\n }\r\n\r\n float deltaLon = lon_2 - lon_1;\r\n\r\n float x = cos(lat_2) * sin(deltaLon);\r\n float y = cos(lat_1) * sin(lat_2) - sin(lat_1) * cos(lat_2) * cos(deltaLon);\r\n\r\n return fmod(rad2deg(atan2(x, y)) + 360, 360);\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Calculate the bearing between two NED coordinates.\r\n\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& ned_1 - First NED coordinate in meters\r\n * const Vector3f& ned_2 - Second NED coordinate in meters\r\n * const bool& angle_unit - Unit of the latitude, longitude, and bearing\r\n angles (rad or degrees)\r\n\r\n Returns:\r\n --------\r\n * float bearing - The bearing between the two given LLA coordinates\r\n*/\r\nfloat bearingNed(const Vector3f& ned_1, const Vector3f& ned_2)\r\n{\r\n float n_1 = ned_1(0);\r\n float e_1 = ned_1(1);\r\n\r\n float n_2 = ned_2(0);\r\n float e_2 = ned_2(1);\r\n\r\n float x = e_2 - e_1;\r\n float y = n_2 - n_1;\r\n\r\n return fmod(rad2deg(atan2(x, y)) + 360, 360);\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Calculate the distance between two LLA coordinates.\r\n\r\n http://www.movable-type.co.uk/scripts/latlong.html\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& lla_1 - First LLA coordinate (altitude in meters)\r\n * const Vector3f& lla_2 - Second LLA coordinate (altitude in meters)\r\n * const bool& angle_unit - Unit of the latitude and longitude angles (rad\r\n or degrees)\r\n\r\n Returns:\r\n --------\r\n * float dist - The distance between the two given LLA coordinates in meters\r\n*/\r\ndouble distanceLla(const Vector3f& lla_1, const Vector3f& lla_2, const bool& angle_unit)\r\n{\r\n float lat_1 = lla_1(0);\r\n float lon_1 = lla_1(1);\r\n\r\n float lat_2 = lla_2(0);\r\n float lon_2 = lla_2(1);\r\n\r\n if (angle_unit == DEGREES)\r\n {\r\n lat_1 = deg2rad(lat_1);\r\n lon_1 = deg2rad(lon_1);\r\n\r\n lat_2 = deg2rad(lat_2);\r\n lon_2 = deg2rad(lon_2);\r\n }\r\n\r\n double deltaLat = lat_2 - lat_1;\r\n double deltaLon = lon_2 - lon_1;\r\n\r\n double _a = (sin(deltaLat / 2) * sin(deltaLat / 2)) + cos(lat_1) * cos(lat_2) * (sin(deltaLon / 2)) * (sin(deltaLon / 2));\r\n\r\n float azimuth = bearingLla(lla_1, lla_2, angle_unit);\r\n float radius = earthAzimRad(lla_1(0), azimuth, angle_unit);\r\n\r\n return 2 * radius * atan2(sqrt(_a), sqrt(1 - _a));\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Calculate the total distance between two NED coordinates.\r\n\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& ned_1 - First NED coordinate in meters\r\n * const Vector3f& ned_2 - Second NED coordinate in meters\r\n\r\n Returns:\r\n --------\r\n * float dist - The total distance between the two given NED coordinates\r\n*/\r\nfloat distanceNed(const Vector3f& ned_1, const Vector3f& ned_2)\r\n{\r\n Vector3f out = ned_2 - ned_1;\r\n return out.norm();\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Calculate the horizontal distance between two NED coordinates.\r\n\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& ned_1 - First NED coordinate in meters\r\n * const Vector3f& ned_2 - Second NED coordinate in meters\r\n\r\n Returns:\r\n --------\r\n * float dist - The horizontal distance between the two given NED coordinates\r\n*/\r\nfloat distanceNedHoriz(const Vector3f& ned_1, const Vector3f& ned_2)\r\n{\r\n Vector2f out;\r\n\r\n out << ned_2(0) - ned_1(0),\r\n ned_2(1) - ned_1(1);\r\n\r\n return out.norm();\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Calculate the vertical distance between two NED coordinates.\r\n\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& ned_1 - First NED coordinate in meters\r\n * const Vector3f& ned_2 - Second NED coordinate in meters\r\n\r\n Returns:\r\n --------\r\n * float dist - The vertical distance between the two given NED coordinates\r\n*/\r\nfloat distanceNedVert(const Vector3f& ned_1, const Vector3f& ned_2)\r\n{\r\n return ned_2(2) - ned_1(2);\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Calculate the total distance between two ECEF coordinates.\r\n\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n https://en.wikipedia.org/wiki/Earth-centered,_Earth-fixed_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& ecef_1 - First ECEF coordinate in meters\r\n * const Vector3f& ecef_2 - Second ECEF coordinate in meters\r\n\r\n Returns:\r\n --------\r\n * float dist - The total distance between the two given ECEF coordinates\r\n*/\r\nfloat distanceEcef(const Vector3f& ecef_1, const Vector3f& ecef_2)\r\n{\r\n Vector3f out = ecef_2 - ecef_1;\r\n return out.norm();\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Calculate the elevation angle between two LLA coordinates.\r\n\r\n http://www.movable-type.co.uk/scripts/latlong.html\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& lla_1 - First LLA coordinate (altitude in meters)\r\n * const Vector3f& lla_2 - Second LLA coordinate (altitude in meters)\r\n * const bool& angle_unit - Unit of the latitude, longitude, and elevation\r\n angles (rad or degrees)\r\n\r\n Returns:\r\n --------\r\n * float elevation - The elevation angle between the two given LLA coordinates\r\n*/\r\nfloat elevationLla(const Vector3f& lla_1, const Vector3f& lla_2, const bool& angle_unit)\r\n{\r\n float lat_1 = lla_1(0);\r\n float lon_1 = lla_1(1);\r\n float alt_1 = lla_1(2);\r\n\r\n float lat_2 = lla_2(0);\r\n float lon_2 = lla_2(1);\r\n float alt_2 = lla_2(2);\r\n\r\n if (angle_unit == DEGREES)\r\n {\r\n lat_1 = deg2rad(lat_1);\r\n lon_1 = deg2rad(lon_1);\r\n\r\n lat_2 = deg2rad(lat_2);\r\n lon_2 = deg2rad(lon_2);\r\n }\r\n\r\n float dist = distanceLla(lla_1, lla_2, angle_unit);\r\n float height = alt_2 - alt_1;\r\n\r\n return rad2deg(atan2(height, dist));\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Calculate the elevation angle between two NED coordinates.\r\n\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& ned_1 - First NED coordinate (altitude in meters)\r\n * const Vector3f& ned_2 - Second NED coordinate (altitude in meters)\r\n * const bool& angle_unit - Unit of the latitude, longitude, and elevation\r\n angles (rad or degrees)\r\n\r\n Returns:\r\n --------\r\n * float elevation - The elevation angle between the two given NED coordinates\r\n*/\r\nfloat elevationNed(const Vector3f& ned_1, const Vector3f& ned_2)\r\n{\r\n float d_1 = -ned_1(2);\r\n float d_2 = -ned_2(2);\r\n\r\n float dist = distanceNed(ned_1, ned_2);\r\n float height = d_2 - d_1;\r\n\r\n return rad2deg(atan2(height, dist));\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Calculate a LLA coordinate based on a given LLA coordinate, distance,\r\n azimuth, and elevation angle.\r\n\r\n http://www.movable-type.co.uk/scripts/latlong.html\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& lla - LLA coordinate (altitude in meters)\r\n * const float& dist - \"As the crow flies\" distance between the two\r\n LLA coordinates in meters\r\n * const float& _azimuth - Azimuth angle between the two LLA coordinates\r\n * const float& _elevation - Elevation angle between the two LLA coordinates\r\n * const bool& angle_unit - Unit of the latitude, longitude, azimuth, and\r\n elevation angles (rad or degrees)\r\n\r\n Returns:\r\n --------\r\n * Vector3f& out - New LLA coordinate (altitude in meters)\r\n*/\r\nVector3f LDAE2lla(const Vector3f& lla, const float& dist, const float& _azimuth, const float& _elevation, const bool& angle_unit)\r\n{\r\n float lat = lla(0);\r\n float lon = lla(1);\r\n float alt = lla(2);\r\n\r\n float azimuth = _azimuth;\r\n float elevation = _elevation;\r\n\r\n if (angle_unit == DEGREES)\r\n {\r\n lat = deg2rad(lat);\r\n lon = deg2rad(lon);\r\n\r\n azimuth = deg2rad(azimuth);\r\n elevation = deg2rad(elevation);\r\n }\r\n\r\n float radius = earthAzimRad(lla(0), _azimuth, angle_unit);\r\n float adj_dist = dist / radius;\r\n\r\n float lat_2 = asin(sin(lat) * cos(adj_dist) + cos(lat) * sin(adj_dist) * cos(azimuth));\r\n float lon_2 = lon + atan2(sin(azimuth) * sin(adj_dist) * cos(lat), cos(adj_dist) - sin(lat) * sin(lat_2));\r\n\r\n Vector3f out;\r\n\r\n out << rad2deg(lat_2),\r\n rad2deg(lon_2),\r\n alt + (dist * tan(elevation));\r\n\r\n return out;\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n Description:\r\n ------------\r\n Calculate a NED coordinate based on a given NED coordinate, distance,\r\n azimuth, and elevation angle.\r\n\r\n https://en.wikipedia.org/wiki/Geographic_coordinate_system\r\n\r\n Arguments:\r\n ----------\r\n * const Vector3f& ned - NED coordinate in meters\r\n * const float& dist - Horizontal distance between the two\r\n NED coordinates in meters\r\n * const float& _azimuth - Azimuth angle between the two NED coordinates\r\n * const float& _elevation - Elevation angle between the two NED coordinates\r\n * const bool& angle_unit - Unit of the azimuth and elevation angles (rad\r\n or degrees)\r\n\r\n Returns:\r\n --------\r\n * Vector3f& out - New NED coordinate in meters\r\n*/\r\nVector3f NDAE2ned(const Vector3f& ned, const float& dist, const float& _azimuth, const float& _elevation, const bool& angle_unit)\r\n{\r\n float n = ned(0);\r\n float e = ned(1);\r\n float d = ned(2);\r\n\r\n float azimuth = _azimuth;\r\n float elevation = _elevation;\r\n\r\n if (angle_unit == DEGREES)\r\n {\r\n azimuth = deg2rad(azimuth);\r\n elevation = deg2rad(elevation);\r\n }\r\n\r\n Vector3f out;\r\n\r\n out << n + dist * cos(azimuth),\r\n e + dist * sin(azimuth),\r\n d + (dist * tan(elevation));\r\n\r\n return out;\r\n}\r\n", "meta": {"hexsha": "c8c15db7ba9508f5d6f207ff478968af284638da", "size": 47344, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/navduino.cpp", "max_stars_repo_name": "PowerBroker2/navduino", "max_stars_repo_head_hexsha": "99275787076204379216123b3707a9f64d1eb6ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-03-21T15:51:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T20:20:45.000Z", "max_issues_repo_path": "src/navduino.cpp", "max_issues_repo_name": "PowerBroker2/navduino", "max_issues_repo_head_hexsha": "99275787076204379216123b3707a9f64d1eb6ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/navduino.cpp", "max_forks_repo_name": "PowerBroker2/navduino", "max_forks_repo_head_hexsha": "99275787076204379216123b3707a9f64d1eb6ce", "max_forks_repo_licenses": ["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.7631430187, "max_line_length": 162, "alphanum_fraction": 0.594753295, "num_tokens": 12555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025231, "lm_q2_score": 0.7905303236047048, "lm_q1q2_score": 0.7507424323301918}} {"text": "#include \n\n#include \n#include \n\n/* @brief QR decomposition from Cholesky decomposition\n * @param[in] A An $m \\times n$ matrix\n * @param[out] R The upper triangular matrix from the QR decomposition of $A$\n * @param[out] Q The orthogonal matrix from the QR decomposition of $A$\n */\nvoid CholeskyQR(const Eigen::MatrixXd &A, Eigen::MatrixXd &R, Eigen::MatrixXd &Q) {\n\tEigen::MatrixXd L = (A.transpose() * A).llt().matrixL();\n\tQ = L.triangularView().solve(A.transpose()).transpose();\n\tR = L.transpose();\n}\n\n/* @brief Direct QR decomposition\n * @param[in] A An $m \\times n$ matrix\n * @param[out] R The upper triangular matrix from the QR decomposition of $A$\n * @param[out] Q The orthogonal matrix from the QR decomposition of $A$\n */\nvoid DirectQR(const Eigen::MatrixXd &A, Eigen::MatrixXd &R, Eigen::MatrixXd &Q) {\n\n\tint m = A.rows();\n\tint n = A.cols();\n\n\tEigen::HouseholderQR qr(A);\n\tQ = qr.householderQ() * Eigen::MatrixXd::Identity(m, n);\n\tR = (Q.transpose() * A);\n}\n\nint main() {\n\tint m = 3;\n\tint n = 2;\n\n\tEigen::MatrixXd A(m,n);\n\tdouble epsilon = 1.e-8;\n\t//A << 3, 5, 1, 9, 7, 1;\n\tA << 1, 1, epsilon, 0, 0, epsilon;\n\tstd::cout << \"A =\" << std::endl << A << std::endl;\n\n\tEigen::MatrixXd R, Q;\n\n\tCholeskyQR(A, R, Q);\n\tstd::cout << \"CholeskyQR: ===========\" << std::endl;\n\tstd::cout << \"R =\" << std::endl << R << std::endl;\n\tstd::cout << \"Q =\" << std::endl << Q << std::endl;\n\n\tDirectQR(A, R, Q);\n\tstd::cout << \"DirectQR: =============\" << std::endl;\n\tstd::cout << \"R =\" << std::endl << R << std::endl;\n\tstd::cout << \"Q =\" << std::endl << Q << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "7c3d9ef4f6e257d708873345495c1e4d874d43df", "size": 1632, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "exercise_3/cholesky_qr.cpp", "max_stars_repo_name": "azurite/numCSE18-code", "max_stars_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-13T19:08:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-13T19:08:32.000Z", "max_issues_repo_path": "exercise_3/cholesky_qr.cpp", "max_issues_repo_name": "azurite/numCSE18-code", "max_issues_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercise_3/cholesky_qr.cpp", "max_forks_repo_name": "azurite/numCSE18-code", "max_forks_repo_head_hexsha": "f7104305375954a0528d366f8460bf8033d20f0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1428571429, "max_line_length": 83, "alphanum_fraction": 0.6035539216, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7506576640744256}} {"text": "/**\n * @file slae.hpp: System of Linear Algebraic Equations utilities.\n *\n * This module contains functions for solving SLAE,\n * particularly for Cube Product Strassen-like algorithm finding.\n *\n * @author Eugene Petkevich\n * @version pre-alpha\n */\n\n#ifndef SLAE_HPP_INCLUDED\n#define SLAE_HPP_INCLUDED\n\n#include \n#include \n\n#include \n\n#include \"utils.hpp\"\n\nusing namespace std;\n\n//=============================================================================\n\n/// All the following functions solve SLAE using different methods.\n\ntemplate \nbool gauss_solve(vector> a, mm_bitset b);\n\nclass Gauss_Presolve_Data;\ntemplate \nvoid gauss_presolve(vector> a, Gauss_Presolve_Data& p);\ntemplate \nbool gauss_solve(const Gauss_Presolve_Data& p, mm_bitset b);\n\ntemplate \nbool binary_solve(const vector>& a, const mm_bitset& b);\n\ntemplate \nbool binary_solve_recursive(const vector>& a, const mm_bitset& b);\n\ntemplate \nbool gauss_solve_randomized(vector> a, mm_vector_with_properties b);\n\ntemplate \nclass Gauss_WP_Presolve_Data;\ntemplate \nbool gauss_wp_presolve(const vector>& a, Gauss_WP_Presolve_Data& p);\ntemplate \nbool gauss_wp_solve(Gauss_WP_Presolve_Data& p, const mm_vector_with_properties& b);\ntemplate \nbool gauss_wp_solve_cached(Gauss_WP_Presolve_Data& p, const mm_vector_with_properties& b);\ntemplate \nbool gauss_wp_solve_fast_cached(Gauss_WP_Presolve_Data& p, const mm_vector_with_properties& b);\n\n//=============================================================================\n\n/// Comparison functions for bitvectors.\n\ntemplate \nbool compare_lexical (const mm_bitset& a, const mm_bitset& b);\n\ntemplate \nbool compare_count (const mm_bitset& a, const mm_bitset& b);\n\ntemplate \nbool compare_combined (const mm_bitset& a, const mm_bitset& b);\n\n//=============================================================================\n//=============================================================================\n\n/**\n * Sovle SLAE by Gaussian elimination.\n *\n * @param a: the coefficient matrix;\n * @param b: the resulting vector;\n *\n * @return if there is a solution.\n */\ntemplate \nbool\ngauss_solve(vector> a, mm_bitset b)\n{\n int r = 0;\n for (int i = 0; i < a.size(); ++i) { // for all columns\n // first we exchange rows if needed, so that a[i][i] = 1\n if (!a[i][r]) {\n int k = r+1;\n while ((k < N) && (!a[i][k])) {\n ++k;\n }\n if (k >= N) {\n continue;\n } else {\n bool tmp = b[k];\n b[k] = b[r];\n b[r] = tmp;\n for (int l = i; l < a.size(); ++l) {\n tmp = a[l][k];\n a[l][k] = a[l][r];\n a[l][r] = tmp;\n }\n }\n }\n // second, we make all coefficients under a[i][i] equal to 0\n for (int j = r+1; j < b.size(); ++j) { // for all rows\n if (a[i][j]) {\n for (int k = i; k < a.size(); ++k) {\n a[k][j] = (a[k][j] != a[k][r]);\n }\n b[j] = (b[j] != b[r]);\n }\n }\n ++r;\n }\n // we check all i from 7 to 15 for zero coefficients\n for (int i = r; i < b.size(); ++i) {\n if (b[i])\n return false;\n }\n return true;\n}\n\n//=============================================================================\n\n/**\n * Data for Gaussian elimination presolve.\n */\nclass Gauss_Presolve_Data {\npublic:\n size_t n; /// Size of the matrix.\n int r;\n vector rows_s;\n vector rows_d;\n vector rows_o;\n};\n\n/**\n * Presolve SLAE by Gaussian elimination.\n *\n * Collects Gaussian elimination operations that are needed\n * to selve a SLAE with a specified matrix.\n *\n * @param a: the coefficient matrix;\n * @param p: varuable to store presolve data;\n */\ntemplate \nvoid\ngauss_presolve(vector> a, Gauss_Presolve_Data & p)\n{\n p.n = a.size();\n p.rows_s.clear();\n p.rows_d.clear();\n p.rows_o.clear();\n int r = 0;\n for (int i = 0; i < a.size(); ++i) { // for all columns\n // first we exchange rows if needed, so that a[i][i] = 1\n if (!a[i][r]) {\n int k = r+1;\n while ((k < N) && (!a[i][k])) {\n ++k;\n }\n if (k >= N) {\n continue;\n } else {\n bool tmp;\n p.rows_s.push_back(r);\n p.rows_d.push_back(k);\n p.rows_o.push_back(true);\n for (int l = i; l < a.size(); ++l) {\n tmp = a[l][k];\n a[l][k] = a[l][r];\n a[l][r] = tmp;\n }\n }\n }\n // second, we make all coefficients under a[i][i] equal to 0\n for (int j = r+1; j < N; ++j) { // for all rows\n if (a[i][j]) {\n for (int k = i; k < a.size(); ++k) {\n a[k][j] = (a[k][j] != a[k][r]);\n }\n p.rows_s.push_back(r);\n p.rows_d.push_back(j);\n p.rows_o.push_back(false);\n }\n }\n ++r;\n }\n p.r = r;\n}\n\n/**\n * Sovle SLAE by Gaussian elimination using precomputed data.\n *\n * @param p: the presolve data;\n * @param b: the resulting vector;\n *\n * @return if there is a solution.\n */\ntemplate \nbool\ngauss_solve(const Gauss_Presolve_Data& p, mm_bitset b)\n{\n for (int i = 0; i < p.rows_o.size(); ++i) {\n if (p.rows_o[i]) {\n bool tmp = b[p.rows_s[i]];\n b[p.rows_s[i]] = b[p.rows_d[i]];\n b[p.rows_d[i]] = tmp;\n } else {\n b[p.rows_d[i]] = (b[p.rows_d[i]] != b[p.rows_s[i]]);\n }\n }\n for (int i = p.r; i < b.size(); ++i) {\n if (b[i])\n return false;\n }\n return true;\n}\n\n//=============================================================================\n\n/**\n * Solve SLAE by trying all solutions.\n *\n * @param a: the coefficient matrix;\n * @param b: the resulting vector;\n *\n * @return if there is a solution.\n */\ntemplate \nbool\nbinary_solve(const vector>& a, const mm_bitset& b)\n{\n uint_least64_t counter;\n uint_least64_t limit = power(2,a.size());\n for (counter = 1; counter < limit; ++counter) {\n boost::dynamic_bitset<> x(a.size(),counter);\n mm_bitset r(0);\n bool is_good = true;\n // we multiply a by x\n for (int i = 0; i < b.size(); ++i) {\n for (int j = 0; j < a.size(); ++j) {\n if (x[j]) {\n r[i] = (r[i] != a[j][i]);\n }\n }\n if (r[i] != b[i]) {\n is_good = false;\n break;\n }\n }\n if (is_good)\n return true;\n }\n return false;\n}\n\n/**\n * Solve SLAE by trying all solutions.\n *\n * @param a: the coefficient matrix;\n * @param b: the resulting vector;\n *\n * @return if there is a solution.\n */\ntemplate \nbool\nbinary_solve(const vector>& a, const mm_vector_with_properties& b)\n{\n vector> sa;\n for (auto& vp: a) {\n sa.push_back(vp.v);\n }\n return binary_solve(sa, b.v);\n}\n\n/**\n * Solve SLAE by trying all solutions and return the result.\n *\n * The SLAE should have a solution.\n *\n * @param a: the coefficient matrix;\n * @param b: the resulting vector;\n *\n * @return solution (if SLAE has no solution, return value could be anything).\n */\ntemplate \nboost::dynamic_bitset<>\nbinary_solve_result(const vector>& a, const mm_bitset& b)\n{\n uint_least64_t counter;\n uint_least64_t limit = power(2,a.size());\n for (counter = 1; counter < limit; ++counter) {\n boost::dynamic_bitset<> x(a.size(),counter);\n mm_bitset r(0);\n bool is_good = true;\n // we multiply a by x\n for (int i = 0; i < b.size(); ++i) {\n for (int j = 0; j < a.size(); ++j) {\n if (x[j]) {\n r[i] = (r[i] != a[j][i]);\n }\n }\n if (r[i] != b[i]) {\n is_good = false;\n break;\n }\n }\n if (is_good)\n return x;\n }\n return boost::dynamic_bitset<>();\n}\n\n//=============================================================================\n\n/**\n * Subroutine for solving SLAE via backtracking.\n *\n * @param a: the coefficient matrix;\n * @param b: the resulting vector;\n * @param depth: backtracking tree current depth;\n * @param current: current value of guessed solution.\n *\n * @return if there is a solution.\n */\ntemplate \nbool\nbinary_solve_explore(const vector>* a, const mm_bitset* b, int depth, const mm_bitset* current)\n{\n if (depth == -1) {\n for (int k = 0; k < N; ++k) {\n if (current->test(k) != b->test(k))\n return false;\n }\n return true;\n } else {\n bool result = binary_solve_explore(a, b, depth-1, current);\n if (result)\n return true;\n mm_bitset* current_add = new mm_bitset();\n for (int k = 0; k < N; ++k) {\n (*current_add)[k] = current->test(k) != (*a)[depth][k];\n }\n result = binary_solve_explore(a, b, depth-1, current_add);\n delete current_add;\n return result;\n }\n}\n\n/**\n * Solve SLAE by trying solutions via backtracking.\n *\n * @param a: the coefficient matrix;\n * @param b: the resulting vector;\n *\n * @return if there is a solution.\n */\ntemplate \nbool\nbinary_solve_recursive(const vector>& a, const mm_bitset& b)\n{\n uint_least64_t depth = a.size()-1;\n mm_bitset* current = new mm_bitset();\n current->reset();\n bool result = binary_solve_explore(&a, &b, depth, current);\n delete current;\n return result;\n}\n\n//=============================================================================\n\n/**\n * TODO\n */\ntemplate \nbool\ngauss_solve_randomized(vector> a, mm_vector_with_properties b)\n{\n return true;\n}\n\n//=============================================================================\n\n/**\n * Compare function to sort bitsets lexicographically.\n *\n * @param N: bitset size;\n */\ntemplate \nbool\ncompare_lexical (const mm_bitset& a, const mm_bitset& b)\n{\n for (int i = 0; i < N; ++i) {\n if (a[i] < b[i]) {\n return true;\n } else if (a[i] > b[i]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Compare function to sort bitsets by number of 1-bits.\n *\n * @param N: bitset size;\n */\ntemplate \nbool\ncompare_count (const mm_bitset& a, const mm_bitset& b)\n{\n return (a.count() < b.count());\n}\n\n/**\n * Compare function to sort bitsets by number of bits,\n * and if it is the same, lexicographically.\n *\n * @param N: bitset size;\n */\ntemplate \nbool\ncompare_combined (const mm_bitset& a, const mm_bitset& b)\n{\n if (a.count() < b.count()) {\n return true;\n } else if (a.count() > b.count()) {\n return false;\n } else {\n for (int i = 0; i < N; ++i) {\n if (a[i] > b[i]) {\n return true;\n } else if (a[i] < b[i]) {\n return false;\n }\n }\n return true;\n }\n}\n\n//=============================================================================\n\n/**\n * Presolve data for Gaussian elimination variant for solving SLAE.\n *\n * @param N: size of result and variable vectors.\n */\ntemplate \nclass Gauss_WP_Presolve_Data {\npublic:\n vector> am; /// Transformed Matrix.\n vector imi;\n map> cache; /// cache with sums of vectors\n mm_vector_with_properties* memo_array; /// cache with sums of vectors\n bool* memo_status; /// cache status\n\n Gauss_WP_Presolve_Data(int f_count);\n ~Gauss_WP_Presolve_Data();\n};\n\n/**\n * Constructor.\n *\n * @param f_count: number of vectors in matrix.\n */\ntemplate \nGauss_WP_Presolve_Data::\nGauss_WP_Presolve_Data(int f_count)\n{\n memo_array = new mm_vector_with_properties[power(2, f_count)];\n memo_status = new bool[power(2, f_count)];\n}\n\n/**\n * Destructor.\n */\ntemplate \nGauss_WP_Presolve_Data::\n~Gauss_WP_Presolve_Data()\n{\n delete [] memo_array;\n delete [] memo_status;\n}\n\n/**\n * Collect operoationsdata for Gaussian elimination variant for solving SLAE.\n *\n * @param N: size of result and variable vectors.\n *\n * @param a: the coefficient matrix;\n * @param p: variable to store presolve data.\n */\ntemplate \nbool\ngauss_wp_presolve(const vector>& a, Gauss_WP_Presolve_Data& p)\n{\n p.am = a;\n p.imi.clear();\n p.cache.clear();\n for (typename vector>::iterator i = p.am.begin(); i != p.am.end();) { // for all columns\n int k = 0;\n while (((k < N) && (!(*i).v[k])) || (find(p.imi.begin(), p.imi.end(), k) != p.imi.end())) {\n ++k;\n }\n if (k == N) { // linearly dependent\n i = p.am.erase(i);\n return false;\n } else { // make 0's all items in a row k except for i'th column\n for (typename vector>::iterator j = p.am.begin(); j != i; ++j) {\n if ((*j).v[k]) {\n (*j).v ^= (*i).v;\n (*j).r ^= (*i).r;\n }\n }\n for (typename vector>::iterator j = i+1; j != p.am.end(); ++j) {\n if ((*j).v[k]) {\n (*j).v ^= (*i).v;\n (*j).r ^= (*i).r;\n }\n }\n p.imi.push_back(k);\n ++i;\n }\n }\n return true;\n}\n\n/**\n * Sovle SLAE by Gaussian elimination using precomputed data.\n *\n * @param N: size of result and variable vectors.\n *\n * @param p: the presolve data;\n * @param b: the resulting vector;\n *\n * @return if there is a solution.\n */\ntemplate \nbool\ngauss_wp_solve(Gauss_WP_Presolve_Data& p, const mm_vector_with_properties& b)\n{\n mm_vector_with_properties c;\n typename vector>::const_iterator j = p.am.begin();\n for (vector::const_iterator i = p.imi.begin(); i != p.imi.end(); ++i) {\n if (b.v[*i]) {\n c.v ^= (*j).v;\n }\n ++j;\n }\n return (c.v == b.v);\n}\n\n/**\n * Sovle SLAE by Gaussian elimination using precomputed data using memoization.\n *\n * @param N: size of result and variable vectors.\n *\n * @param p: the presolve data;\n * @param b: the resulting vector;\n *\n * @return if there is a solution.\n */\ntemplate \nbool\ngauss_wp_solve_cached(Gauss_WP_Presolve_Data& p, const mm_vector_with_properties& b)\n{\n /*\n c.r.reset();\n j = p.am.begin();\n for (vector::const_iterator i = p.imi.begin(); i != p.imi.end(); ++i) {\n if (b.v[*i]) {\n c.r ^= (*j).r;\n }\n ++j;\n }\n */\n // first check number of ones\n /*\n if (c.r.count() != b.r_count) {\n return false;\n }\n */\n // then every bit\n /*\n if (c.r != b.r)\n return false;\n */\n int matrix_multiplier = 0;\n for (vector::const_iterator i = p.imi.begin(); i != p.imi.end(); ++i) {\n matrix_multiplier <<= 1;\n matrix_multiplier += b.v[*i];\n }\n typename map>::const_iterator memo_result = p.cache.find(matrix_multiplier);\n if (memo_result != p.cache.end()) {\n return (memo_result->second.v == b.v);\n } else {\n mm_vector_with_properties c;\n typename vector>::const_iterator j = p.am.begin();\n for (vector::const_iterator i = p.imi.begin(); i != p.imi.end(); ++i) {\n if (b.v[*i]) {\n c.v ^= (*j).v;\n }\n ++j;\n }\n p.cache[matrix_multiplier] = c;\n return (c.v == b.v);\n }\n // first check number of ones\n /*\n if (c.v.count() != b.v_count) {\n return false;\n }\n */\n}\n\n/**\n * Sovle SLAE by Gaussian elimination using precomputed data using memoization.\n *\n * @param N: size of result and variable vectors.\n *\n * @param p: the presolve data;\n * @param b: the resulting vector;\n *\n * @return if there is a solution.\n */\ntemplate \nbool\ngauss_wp_solve_fast_cached(Gauss_WP_Presolve_Data& p, const mm_vector_with_properties& b)\n{\n int matrix_multiplier = 0;\n for (vector::const_iterator i = p.imi.begin(); i != p.imi.end(); ++i) {\n matrix_multiplier <<= 1;\n matrix_multiplier += b.v[*i];\n }\n if (p.memo_status[matrix_multiplier]) {\n return (p.memo_array[matrix_multiplier].v == b.v);\n } else {\n mm_vector_with_properties c;\n typename vector>::const_iterator j = p.am.begin();\n for (vector::const_iterator i = p.imi.begin(); i != p.imi.end(); ++i) {\n if (b.v[*i]) {\n c.v ^= (*j).v;\n }\n ++j;\n }\n p.memo_array[matrix_multiplier] = c;\n p.memo_status[matrix_multiplier] = true;\n return (c.v == b.v);\n }\n}\n\n//=============================================================================\n\n#endif // SLAE_HPP_INCLUDED\n", "meta": {"hexsha": "8ee21fa2602b62b733b2b4afe5cc2b27c4124c23", "size": 17738, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "slae.hpp", "max_stars_repo_name": "nasedil/checkspanfast", "max_stars_repo_head_hexsha": "f274660211d9b24e64d7632552cad81795c20cd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "slae.hpp", "max_issues_repo_name": "nasedil/checkspanfast", "max_issues_repo_head_hexsha": "f274660211d9b24e64d7632552cad81795c20cd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slae.hpp", "max_forks_repo_name": "nasedil/checkspanfast", "max_forks_repo_head_hexsha": "f274660211d9b24e64d7632552cad81795c20cd1", "max_forks_repo_licenses": ["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.99847793, "max_line_length": 121, "alphanum_fraction": 0.5239598602, "num_tokens": 4582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.750657661123555}} {"text": "// NormalFunction.cpp\n//\n// Some exact formulae.\n//\n// (C) Datasim Education BV 2011\n//\n\n#include \n#include \nusing namespace std;\n#include \n#include // For non-member functions of distributions\nusing namespace boost::math;\n\nusing namespace boost::math;\n\ndouble N(double x)\n{\n\n\tnormal_distribution<> myNormal(0.0, 1.0); \n\n\treturn cdf(myNormal, x);\n\n}\n\ndouble n(double x)\n{\n\n\tnormal_distribution<> myNormal(0.0, 1.0); \n\n\treturn pdf(myNormal, x);\n\n}\n\n\n\n\nint main()\n{\n\n\tdouble x = 2.0;\n\tcout << \"pdf: \" << n(x) << \", cdf: \" << N(x) << endl;\n\t\n\treturn 0;\n}\n", "meta": {"hexsha": "44983170e41583cd5ca49dde6a9bed19a7b18ad8", "size": 637, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Level_9/Level9Code/VI.3 Option Pricing/NormalFunction.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/Level9Code/VI.3 Option Pricing/NormalFunction.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/Level9Code/VI.3 Option Pricing/NormalFunction.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": 13.847826087, "max_line_length": 84, "alphanum_fraction": 0.6593406593, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.7506576602356358}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n\n#include \"aby3-ML/Regression.h\"\n#include \"aby3-ML/LinearModelGen.h\"\n\n#include \"aby3-ML/aby3ML.h\"\n#include \"aby3-ML/PlainML.h\"\n\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace oc;\nnamespace aby3\n{\n\n\tint logistic_plain_main(CLP& cmd)\n\t{\n\t\tauto N = cmd.getOr(\"N\", 10000);\n\t\tauto D = cmd.getOr(\"D\", 1000);\n\t\tauto B = cmd.getOr(\"B\", 128);\n\t\tauto IT = cmd.getOr(\"I\", 10000);\n\t\tauto testN = cmd.getOr(\"testN\", 1000);\n\n\t\tPRNG prng(toBlock(1));\n\t\tLogisticModelGen gen;\n\n\t\teMatrix model(D, 1);\n\t\tfor (u64 i = 0; i < D; ++i)\n\t\t{\n\t\t\tmodel(i, 0) = prng.get() % 10;\n\t\t\tstd::cout << model(i, 0) << \" \";\n\t\t}\n\n\t\tstd::cout << std::endl;\n\t\tgen.setModel(model);\n\n\n\n\t\teMatrix train_data(N, D), train_label(N, 1);\n\t\teMatrix test_data(testN, D), test_label(testN, 1);\n\t\tgen.sample(train_data, train_label);\n\t\tgen.sample(test_data, test_label);\n\n\n\t\tstd::cout << \"training __\" << std::endl;\n\n\t\tRegressionParam params;\n\t\tparams.mBatchSize = B;\n\t\tparams.mIterations = IT;\n\t\tparams.mLearningRate = 1.0 / (1 << 3);\n\t\tPlainML engine;\n\n\t\teMatrix W2(D, 1);\n\t\tW2.setZero();\n\t\t//engine.mPrint = cmd.isSet(\"print\");\n\n\t\tSGD_Logistic(params, engine, train_data, train_label, W2, &test_data, &test_label);\n\n\t\tfor (u64 i = 0; i < D; ++i)\n\t\t{\n\t\t\tstd::cout << i << \" \" << gen.mModel(i, 0) << \" \" << W2(i, 0) << std::endl;\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\n\n\tint logistic_main_3pc_sh(int N, int dim, int B, int IT, int testN, int pIdx, bool print, CLP& cmd, Session& chlPrev, Session& chlNext)\n\t{\n\n\t\tPRNG prng(toBlock(1));\n\t\tLogisticModelGen gen;\n\n\t\teMatrix model(dim, 1);\n\t\tfor (u64 i = 0; i < std::min(dim, 10); ++i)\n\t\t{\n\t\t\tmodel(i, 0) = prng.get() % 10;\n\t\t}\n\t\tgen.setModel(model);\n\n\t\teMatrix val_train_data(N, dim), val_train_label(N, 1), val_W2(dim, 1);\n\t\teMatrix val_test_data(testN, dim), val_test_label(testN, 1);\n\t\tgen.sample(val_train_data, val_train_label);\n\t\tgen.sample(val_test_data, val_test_label);\n\t\tval_W2.setZero();\n\n\t\tRegressionParam params;\n\t\tparams.mBatchSize = B;\n\t\tparams.mIterations = IT;\n\t\tparams.mLearningRate = 1.0 / (1 << 3);\n\n\t\tconst Decimal D = D16;\n\t\taby3ML p;\n\n\t\tp.init(pIdx, chlPrev, chlNext, toBlock(pIdx));\n\n\t\t//p.mPrint = cmd.isSet(\"print\");\n\n\t\tsf64Matrix train_data, train_label, W2, test_data, test_label;\n\n\t\tif (pIdx == 0)\n\t\t{\n\t\t\ttrain_data = p.localInput(val_train_data);\n\t\t\ttrain_label = p.localInput(val_train_label);\n\t\t\tW2 = p.localInput(val_W2);\n\t\t\ttest_data = p.localInput(val_test_data);\n\t\t\ttest_label = p.localInput(val_test_label);\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttrain_data = p.remoteInput(0);\n\t\t\ttrain_label = p.remoteInput(0);\n\t\t\tW2 = p.remoteInput(0);\n\t\t\ttest_data = p.remoteInput(0);\n\t\t\ttest_label = p.remoteInput(0);\n\t\t}\n\n\n\t\tp.mPreproNext.resetStats();\n\t\tp.mPreproPrev.resetStats();\n\n\t\tauto preStart = std::chrono::system_clock::now();\n\n\t\tp.preprocess((B + dim) * IT, D);\n\n\t\tdouble preBytes = p.mPreproNext.getTotalDataSent() + p.mPreproPrev.getTotalDataSent();\n\n\n\t\tp.mNext.resetStats();\n\t\tp.mPrev.resetStats();\n\n\n\t\tauto start = std::chrono::system_clock::now();\n\n\t\tif (cmd.isSet(\"noOnline\") == false)\n\t\t\tSGD_Logistic(params, p, train_data, train_label, W2);\n\t\t//val_W2 = p.reveal(W2);\n\n\t\tauto end = std::chrono::system_clock::now();\n\n\n\t\t//engine.sync();\n\t\tauto now = std::chrono::system_clock::now();\n\t\tauto preSeconds = std::chrono::duration_cast(start - preStart).count() / 1000.0;\n\t\tauto seconds = std::chrono::duration_cast(now - start).count() / 1000.0;\n\n\t\tdouble bytes = p.mNext.getTotalDataSent() + p.mPrev.getTotalDataSent();\n\n\t\tif (print)\n\t\t{\n\t\t\tostreamLock ooo(std::cout);\n\t\t\tooo << \"N: \" << N << \" D:\" << dim << \" B:\" << B << \" IT:\" << IT << \" => \"\n\t\t\t\t<< (double(IT) / seconds) << \" iters/s \" << (bytes * 8 / 1024 / 2024) / seconds << \" Mbps\"\n\t\t\t\t<< \" offline: \" << (double(IT) / preSeconds) << \" iters/s \" << (preBytes * 8 / 1024 / 2024) / preSeconds << \" Mbps\" << std::endl;\n\t\t}\n\n\n\t\tauto w2Val = p.reveal(W2);\n\n\t\tif (print)\n\t\t{\n\n\t\t\tfor (u64 i = 0; i < dim; ++i)\n\t\t\t{\n\t\t\t\tstd::cout << i << \" \" << gen.mModel(i, 0) << \" \" << w2Val(i, 0) << std::endl;\n\t\t\t}\n\t\t}\n\n\n\t\treturn 0;\n\t}\n\n\n\tint logistic_main_3pc_sh(oc::CLP & cmd)\n\t{\n\n\t\tauto N = cmd.getManyOr(\"N\", { 10000 });\n\t\tauto D = cmd.getManyOr(\"D\", { 1000 });\n\t\tauto B = cmd.getManyOr(\"B\", { 128 });\n\t\tauto IT = cmd.getManyOr(\"I\", { 10000 });\n\t\tauto testN = cmd.getOr(\"testN\", 1000);\n\n\t\tIOService ios(cmd.isSet(\"p\") ? 2 : 6);\n\n\t\tstd::vector thrds;\n\t\tfor (u64 i = 0; i < 3; ++i)\n\t\t{\n\t\t\tif (cmd.isSet(\"p\") == false || cmd.get(\"p\") == i)\n\t\t\t{\n\t\t\t\tthrds.emplace_back(std::thread([i, N, D, B, IT, testN, &cmd, &ios]() {\n\n\t\t\t\t\tauto next = (i + 1) % 3;\n\t\t\t\t\tauto prev = (i + 2) % 3;\n\t\t\t\t\tauto cNameNext = std::to_string(std::min(i, next)) + std::to_string(std::max(i, next));\n\t\t\t\t\tauto cNamePrev = std::to_string(std::min(i, prev)) + std::to_string(std::max(i, prev));\n\n\t\t\t\t\tauto modeNext = i < next ? SessionMode::Server : SessionMode::Client;\n\t\t\t\t\tauto modePrev = i < prev ? SessionMode::Server : SessionMode::Client;\n\n\n\t\t\t\t\tauto portNext = 1212 + std::min(i, next);\n\t\t\t\t\tauto portPrev = 1212 + std::min(i, prev);\n\n\t\t\t\t\tSession epNext(ios, \"127.0.0.1\", portNext, modeNext, cNameNext);\n\t\t\t\t\tSession epPrev(ios, \"127.0.0.1\", portPrev, modePrev, cNamePrev);\n\n\t\t\t\t\tstd::cout << \"party \" << i << \" next \" << portNext << \" mode=server?:\" << (modeNext == SessionMode::Server) << \" name \" << cNameNext << std::endl;\n\t\t\t\t\tstd::cout << \"party \" << i << \" prev \" << portPrev << \" mode=server?:\" << (modePrev == SessionMode::Server) << \" name \" << cNamePrev << std::endl;\n\t\t\t\t\tauto chlNext = epNext.addChannel();\n\t\t\t\t\tauto chlPrev = epPrev.addChannel();\n\n\t\t\t\t\tchlNext.waitForConnection();\n\t\t\t\t\tchlPrev.waitForConnection();\n\n\t\t\t\t\tchlNext.send(i);\n\t\t\t\t\tchlPrev.send(i);\n\t\t\t\t\tu64 prevAct, nextAct;\n\t\t\t\t\tchlNext.recv(nextAct);\n\t\t\t\t\tchlPrev.recv(prevAct);\n\n\t\t\t\t\tif (next != nextAct)\n\t\t\t\t\t\tstd::cout << \" bad next party idx, act: \" << nextAct << \" exp: \" << next << std::endl;\n\t\t\t\t\tif (prev != prevAct)\n\t\t\t\t\t\tstd::cout << \" bad prev party idx, act: \" << prevAct << \" exp: \" << prev << std::endl;\n\n\t\t\t\t\tostreamLock(std::cout) << \"party \" << i << \" start\" << std::endl;\n\n\t\t\t\t\tauto print = cmd.isSet(\"p\") || i == 0;\n\n\t\t\t\t\tfor (auto n : N)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (auto d : D)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor (auto b : B)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfor (auto it : IT)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tlogistic_main_3pc_sh(n, d, b, it, testN, i, print, cmd, epPrev, epNext);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t}));\n\t\t\t}\n\t\t}\n\n\t\tfor (auto& t : thrds)\n\t\t\tt.join();\n\n\t\treturn 0;\n\t}\n\n}\n", "meta": {"hexsha": "7cf7b73ca0a795ea9154fc94d5549241f962ad07", "size": 6848, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aby3-ML/main-logistic.cpp", "max_stars_repo_name": "vincehong/aby3", "max_stars_repo_head_hexsha": "1a5277b37249545e967fc58a9235666a2453c104", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 121.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T01:35:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T12:53:17.000Z", "max_issues_repo_path": "aby3-ML/main-logistic.cpp", "max_issues_repo_name": "vincehong/aby3", "max_issues_repo_head_hexsha": "1a5277b37249545e967fc58a9235666a2453c104", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2020-01-21T16:47:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T12:41:22.000Z", "max_forks_repo_path": "aby3-ML/main-logistic.cpp", "max_forks_repo_name": "vincehong/aby3", "max_forks_repo_head_hexsha": "1a5277b37249545e967fc58a9235666a2453c104", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 36.0, "max_forks_repo_forks_event_min_datetime": "2019-09-05T08:35:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T11:57:22.000Z", "avg_line_length": 25.552238806, "max_line_length": 151, "alphanum_fraction": 0.5959404206, "num_tokens": 2300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.750481715865343}} {"text": "/**\n * @file exponentialintegrator.cc\n * @brief NPDE homework ExponentialIntegrator code\n * @author Unknown, Oliver Rietmann\n * @date 04.04.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"exponentialintegrator.h\"\n\n#include \n#include \n#include \n\nnamespace ExponentialIntegrator {\n\n//! \\brief Function $\\phi$ used in the Exponential Euler\n//! single step method for an autonomous ODE.\nEigen::MatrixXd phim(const Eigen::MatrixXd &Z) {\n int n = Z.cols();\n assert(n == Z.rows() && \"Matrix must be square.\");\n Eigen::MatrixXd C(2 * n, 2 * n);\n C << Z, Eigen::MatrixXd::Identity(n, n), Eigen::MatrixXd::Zero(n, 2 * n);\n return C.exp().block(0, n, n, n);\n}\n\n} // namespace ExponentialIntegrator\n", "meta": {"hexsha": "94151cfd4374987a0fd55d0debe720454288328a", "size": 759, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ExponentialIntegrator/templates/exponentialintegrator.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/ExponentialIntegrator/templates/exponentialintegrator.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/ExponentialIntegrator/templates/exponentialintegrator.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1071428571, "max_line_length": 75, "alphanum_fraction": 0.6930171278, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.750433619583116}} {"text": "#include \n#include \n#include \n\n\ntemplate \nmatrix gramschmidt(const matrix &A){\n\tunsigned n=A.cols();\n\tmatrix Q=A;\n\tQ.col(0).normalize();\n\n\tfor(int i=1;i\n#include \n#include \n#include \n#include \n\n\n/**\n * Compute fibonacci number for 2**i mod m. Using double and add method.\n */\nNTL::ZZ fibonacci_mod(int i, const NTL::ZZ& m) {\n NTL::ZZ x;\n x = 0;\n NTL::ZZ y;\n y = 1;\n\n NTL::ZZ tmp;\n\n // add for the first 1\n tmp = x;\n x = y;\n y = (tmp + y) % m;\n\n while (true) {\n // double for each 0\n tmp = x;\n x = x*(2*y-x) % m;\n y = (tmp * tmp + y * y) % m;\n\n if (i == 1) {\n return x;\n }\n i -= 1;\n }\n}\n\nint main(int argc, char **argv) {\n // program takes two ints as arguments for the search bounds\n if (argc != 3)\n return 1;\n\n // get search bounds from arguments\n uint lower_bound = std::stoll(argv[1]);\n uint upper_bound = std::stoll(argv[2]);\n\n if (lower_bound < 2) {\n lower_bound = 2;\n }\n\n std::cout << \"lower bound: \" << lower_bound << std::endl;\n std::cout << \"upper bound: \" << upper_bound << std::endl;\n\n // start clock\n auto start = std::chrono::steady_clock::now();\n\n // vector of resulting pseudoprimes\n std::vector results;\n\n NTL::ZZ two;\n two = 2;\n\n for (uint i = lower_bound; i <= upper_bound; i++) {\n NTL::ZZ n; // n = 2**i-1\n n = 2;\n n = n << i-1;\n n -= 1;\n\n NTL::ZZ tmp;\n\n // fermat test\n tmp = NTL::PowerMod(two, n - 1, n);\n if (tmp != 1) {\n continue;\n }\n\n // lucas test\n tmp = fibonacci_mod(i, n);\n if (tmp != 0) {\n continue;\n }\n\n std::cout << \"found: \" << i << std::endl;\n results.push_back(n);\n }\n\n // stop clock\n auto stop = std::chrono::steady_clock::now();\n auto duration = std::chrono::duration_cast(stop - start).count();\n std::cout << \"duration (seconds): \" << duration << std::endl;\n\n // write results to file\n std::ofstream f (\"results.txt\", std::ios::out | std::ios::trunc);\n f << \"lower bound: \" << lower_bound << std::endl;\n f << \"upper bound: \" << upper_bound << std::endl;\n for (const NTL::ZZ& p: results) {\n f << \"found: \" << p << std::endl;\n }\n f << \"duration (seconds): \" << duration << std::endl;\n f.close();\n\n return 0;\n}\n", "meta": {"hexsha": "8e303ab6dc666b4eded03348b9a1109294cee61f", "size": 2309, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "power_two/case1.cpp", "max_stars_repo_name": "okrcma/pseudoprimes", "max_stars_repo_head_hexsha": "a700c3dd2d16e11bb460314be7683828411e0458", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "power_two/case1.cpp", "max_issues_repo_name": "okrcma/pseudoprimes", "max_issues_repo_head_hexsha": "a700c3dd2d16e11bb460314be7683828411e0458", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "power_two/case1.cpp", "max_forks_repo_name": "okrcma/pseudoprimes", "max_forks_repo_head_hexsha": "a700c3dd2d16e11bb460314be7683828411e0458", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4174757282, "max_line_length": 91, "alphanum_fraction": 0.4980511044, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7503083648197159}} {"text": "#include \n#include \n#include \n\nusing Eigen::VectorXd;\nusing Eigen::MatrixXd;\nusing namespace LBFGSpp;\n\nclass Rosenbrock\n{\nprivate:\n int n;\npublic:\n Rosenbrock(int n_) : n(n_) {}\n double operator()(const VectorXd& x, VectorXd& grad)\n {\n double fx = 0.0;\n for(int i = 0; i < n; i += 2)\n {\n double t1 = 1.0 - x[i];\n double t2 = 10 * (x[i + 1] - x[i] * x[i]);\n grad[i + 1] = 20 * t2;\n grad[i] = -2.0 * (x[i] * grad[i + 1] + t1);\n fx += t1 * t1 + t2 * t2;\n }\n assert( ! std::isnan(fx) );\n return fx;\n }\n};\n\nint main()\n{\n LBFGSParam param;\n LBFGSSolver solver(param);\n\n for( int n=2; n <= 16; n += 2 )\n {\n std::cout << \"n = \" << n << std::endl;\n Rosenbrock fun(n);\n for( int test=0; test < 1024; test++ )\n {\n VectorXd x = VectorXd::Random(n);\n double fx;\n int niter = solver.minimize(fun, x, fx);\n\n assert( ( (x.array() - 1.0).abs() < 1e-4 ).all() );\n }\n std::cout << \"Test passed!\" << std::endl << std::endl;\n }\n\n return 0;\n}\n", "meta": {"hexsha": "a74d6fee4da7f990704848754ce77488e39ec2f8", "size": 1218, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example-rosenbrock-bracketing.cpp", "max_stars_repo_name": "storypku/LBFGSpp", "max_stars_repo_head_hexsha": "68068e063303ed6abbebf767c6440144795c0b76", "max_stars_repo_licenses": ["MIT"], "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-rosenbrock-bracketing.cpp", "max_issues_repo_name": "storypku/LBFGSpp", "max_issues_repo_head_hexsha": "68068e063303ed6abbebf767c6440144795c0b76", "max_issues_repo_licenses": ["MIT"], "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-rosenbrock-bracketing.cpp", "max_forks_repo_name": "storypku/LBFGSpp", "max_forks_repo_head_hexsha": "68068e063303ed6abbebf767c6440144795c0b76", "max_forks_repo_licenses": ["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.9811320755, "max_line_length": 63, "alphanum_fraction": 0.4704433498, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7502167162832953}} {"text": "#include \n#include \n#include \n#include \n#include \n\n#include \"Derivative.h\"\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nusing Eigen::Derivative;\n\nusing std::function;\nusing std::vector;\n\nVectorXd LevenbergMarquardt(vector fs, VectorXd x){\n int x_size = x.size(), f_size = fs.size();\n\n vector< vector > Jac( f_size, vector(x_size) );\n \n for(int lf = 0;lf < f_size;lf++)\n for(int lx = 0;lx < x_size;lx++)\n Jac[lf][lx] = fs[lf].diffPartial(lx);\n \n // Set eps to be very larg\n double mu = 0.01, eps = 10000000;\n\n MatrixXd I = MatrixXd::Identity(x_size, x_size);\n\n for(int iter = 0;iter < 200;iter++){\n MatrixXd J(f_size, x_size);\n for(int lf = 0;lf < f_size;lf++)\n for(int lx = 0;lx < x_size;lx++)\n J(lf, lx) = Jac[lf][lx](x);\n\n VectorXd rx(f_size);\n for(int lf = 0;lf < f_size;lf++)\n rx[lf] = fs[lf](x);\n\n double rx_norm = rx.norm();\n\n VectorXd delta = (mu*I + J.transpose()*J).inverse()*J.transpose()*rx;\n x -= delta;\n\n if(eps < rx_norm)\n mu *= 2;\n else if(eps > rx_norm)\n mu /= 2;\n\n if(rx_norm < 0.0001 or delta.norm() < 0.0001)\n break;\n\n eps = rx_norm;\n }\n\n return x;\n}\n\nint main(){\n // Solve : xx + yy + zz = 2\n // x + y + 2*z = 1\n\n Derivative x = Derivative::Variable(0),\n y = Derivative::Variable(1),\n z = Derivative::Variable(2);\n\n Derivative f1 = x*x + y*y + z*z - 2, f2 = x + y + 2*z - 1;\n\n VectorXd v(3);\n v << 1, 1, 1;\n\n std::cout << LevenbergMarquardt({f1, f2}, v).transpose() << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "7aed25e320ac3370e7029a336efb8e0c3fdec53a", "size": 1762, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/levenberg-marquardt.cpp", "max_stars_repo_name": "mudream4869/eigen-derivative", "max_stars_repo_head_hexsha": "c45c9bd1fe781831aaf42fe798c7d6c1a3d568ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/levenberg-marquardt.cpp", "max_issues_repo_name": "mudream4869/eigen-derivative", "max_issues_repo_head_hexsha": "c45c9bd1fe781831aaf42fe798c7d6c1a3d568ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/levenberg-marquardt.cpp", "max_forks_repo_name": "mudream4869/eigen-derivative", "max_forks_repo_head_hexsha": "c45c9bd1fe781831aaf42fe798c7d6c1a3d568ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8831168831, "max_line_length": 77, "alphanum_fraction": 0.5283768445, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7501950874761983}}